21xrx.com
2024-06-02 19:39:33 Sunday
登录
文章检索 我的文章 写文章
C语言一句话中有多少个单词
2023-06-15 13:55:48 深夜i     --     --
C语言 字符串处理 分割 循环 单词个数

在使用C语言编程时,我们经常需要对字符串进行操作。在实际开发中,经常需要统计一句话中有多少个单词。那么,如何用C语言来快速地统计一句话中的单词个数呢?

在C语言中,可以使用字符串处理函数和循环语句来完成这个任务。首先,可以使用strtok函数将字符串分割成单词。然后,可以使用循环语句来统计单词的个数。具体实现可以参考以下代码:


#include

#include

int countWords(char* sentence) {

  int count = 0;

  char* token = strtok(sentence, " ");

  while (token != NULL) {

    count++;

    token = strtok(NULL, " ");

  }

  return count;

}

int main() {

  char sentence[] = "Hello world, how are you?";

  int words = countWords(sentence);

  printf("The sentence '%s' has %d words.\n", sentence, words);

  return 0;

}

在上述代码中,countWords函数用于统计单词个数。在该函数中,首先将句子使用空格分割成单词,然后利用while循环对单词进行逐一统计。最后返回单词个数即可。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复