请问怎么统计指定单词的个数
eg:输入两行
cat cat dog
dog dog cat
统计cat的个数
谢谢
#include <stdio.h>
#include <string.h>
int main()
{
// 要统计的单词
char word[] = "cat";
// 初始化计数器
int count = 0;
// 定义行缓冲区和单词缓冲区
char line[1024];
char word_buf[1024];
// 使用 fgets 读取输入的每一行
while (fgets(line, sizeof(line), stdin))
{
// 将行复制到单词缓冲区
strcpy(word_buf, line);
// 定义单词指针
char *word_ptr = word_buf;
// 遍历单词缓冲区中的每一个单词
while (sscanf(word_ptr, "%s", word_buf) == 1)
{
// 如果找到了要统计的单词,则将计数器加 1
if (strcmp(word_buf, word) == 0)
count++;
// 将单词指针设置为当前单词的下一个字符
word_ptr += strlen(word_buf);
}
}
// 打印统计的个数
printf("%s 出现的个数: %d\n", word, count);
return 0;
}