c预言+请你编写一个函数,输入是一小段的英文,输出是它的英文数量?

如题所述

下面是一个简单的 C 语言函数,可以计算一小段英文中的单词数(假设单词之间用空格隔开):
#include <stdio.h>
#include <ctype.h>
int count_words(char *s) {
int count = 0;
int in_word = 0;
for (; *s; s++) {
if (isspace(*s)) {
in_word = 0;
} else if (!in_word) {
in_word = 1;
count++;
}
}
return count;
}
int main() {
char s[] = "Hello world! How are you?";
int count = count_words(s);
printf("Word count: %d\n", count);
return 0;
}

在上面的例子中,count_words() 函数接收一个指向字符数组的指针,该数组包含输入的英文字符串。该函数使用一个 count 变量来计数单词数量,使用一个 in_word 变量来跟踪当前字符是否处于单词中。遍历字符串中的每个字符,如果字符为空格,则设置 in_word 变量为 0;如果字符不为空格且 in_word 变量为 0,则将 in_word 变量设置为 1,并将 count 变量加 1。最后,函数返回 count 变量,表示输入字符串中的单词数量。
在主函数中,我们定义了一个包含输入字符串的字符数组 s,然后将其传递给 count_words() 函数来计算单词数。最后,使用 printf() 函数输出单词数量。
温馨提示:答案为网友推荐,仅供参考
相似回答