我有一個程式,我為它撰寫一個文本,它計算其中的字母數、單詞數和句子數,但我想問用戶一個問題,然后分配結果或將其組合成三個陣列然后輸出一次結果,而不是每次都要求用戶分別計算字母,單詞,以及銳度上的句子
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
// character count
string text = get_string("text: ");
int number1 = 0;
for (int i = 0; i < strlen(text); i ) {
if (text[i] != ' ' && isalpha(text[i])) {
number1 ;
}
}
// Word counting calculator
string words = get_string("text: ");
int number2 = 0;
for (int i = 0; i < strlen(words); i ) {
if (words[i] == ' ') {
number2 ;
}
}
// Calculate the number of sentences
string sentences = get_string("text: ");
int number3 = 0;
for (int i = 0; i < strlen(sentences); i ) {
if (sentences[i] == '?' || sentences[i] == '!' || sentences[i] == '.') {
number3 ;
}
}
printf("%i %i %i\n", number1, number2, number3);
}
uj5u.com熱心網友回復:
但是我想問用戶一個問題,然后將結果分發或將其組合成三個陣列然后輸出一次結果,而不是每次都要求用戶分別計算字母,單詞和句子
在這種情況下,不要再次要求輸入:
...
// character count
string text = get_string("text: ");
int number1 = 0;
for (int i = 0; i < strlen(text); i ) {
if (text[i] != ' ' && isalpha(text[i])) {
number1 ;
}
}
// Word counting calculator
int number2 = 0;
for (int i = 0; i < strlen(text); i ) {
if (text[i] == ' ') {
number2 ;
}
}
// Calculate the number of sentences
int number3 = 0;
for (int i = 0; i < strlen(text); i ) {
if (text[i] == '?' || text[i] == '!' || text[i] == '.') {
number3 ;
}
}
然后你甚至可以將所有回圈組合成一個回圈:
int number1 = 0;
int number2 = 0;
int number3 = 0;
string text = get_string("text: ");
for (int i = 0; i < strlen(text); i ) {
// character count
if (text[i] != ' ' && isalpha(text[i])) {
number1 ;
}
// Word counting calculator
if (text[i] == ' ') {
number2 ;
}
// Calculate the number of sentences
if (text[i] == '?' || text[i] == '!' || text[i] == '.') {
number3 ;
}
}
uj5u.com熱心網友回復:
我不明白計數字母和組合字串之間的關系。但無論如何,您可以使用 <string.h> 中的內置函式,例如,您可以使用以下方法組合兩個字串: strcat(); .
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494178.html
上一篇:通過拆分向量創建矩陣
