2024年1月15日发(作者:)
统计单词的数量c语言
以下是一个示例函数,可以用来统计一个字符串中的单词数量:
```c
#include
int countWords(char *str) {
int count = 0;
int state = 0;
while (*str) {
if (*str == ' ' || *str == 'n' || *str == 't') {
state = 0;
} else if (state == 0) {
state = 1;
count++;
}
str++;
}
return count;
}
int main() {
char str[] = "Hello World, how are you?";
int wordCount = countWords(str);
printf("The number of words in the string is: %dn", wordCount);
return 0;
}
```
在这个例子中,我们使用了一个状态变量来跟踪当前是否在一个单词内。如果遇到空格、换行符或制表符,则将状态更改为0,否则如果之前的状态为0,表示遇到一个新的单词,将计数增加1。最后,返回计数作为单词数量。在主函数中,我们使用一个字符串来测试函数,并输出结果。
发布者:admin,转转请注明出处:http://www.yc00.com/web/1705252377a1401910.html
评论列表(0条)