福多乐 2022-12-26 11:50 采纳率: 40%
浏览 9
已结题

怎么统计指定单词的个数

请问怎么统计指定单词的个数
eg:输入两行
cat cat dog
dog dog cat
统计cat的个数
谢谢

  • 写回答

1条回答 默认 最新

  • 流比 2022-12-26 11:59
    关注
    
    #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;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 1月3日
  • 已采纳回答 12月26日
  • 创建了问题 12月26日