统计单词的数量c语言

统计单词的数量c语言


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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信