C语言 如何将用户输入的字符串连接到三个数组并打印结果?



我有一个程序,我写一个文本,它计算其中的字母数量,单词数量和句子数量,但我想问用户一个问题,然后分配结果或将其组合成三个数组,然后输出一次结果,而不是要求用户每次分别计算字母,单词和句子的清晰度

#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 %in", number1, number2, number3);
}

但我想问用户一个问题,然后分配结果或将其组合成三个数组,然后输出一次结果,而不是要求用户每次分别计算字母,单词和句子

在这种情况下,不要再要求输入:

...
//  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++;
}
}

我不明白计数字母和组合字符串之间的关系。但无论如何,你可以使用<string。h>例如,你可以使用strcat()来组合两个字符串:.

最新更新