You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言编写算法找出并统计字符串中的重复单词?

统计字符串中所有重复单词的C语言实现

要实现统计字符串中所有重复单词的功能,我们可以通过拆分字符串提取单词,再用结构体数组记录每个单词的出现次数来完成。以下是完整实现,同时修复了原代码中gets()(已废弃)的安全问题:

#include <stdio.h>
#include <string.h>

// 定义结构体存储单词和对应计数
typedef struct {
    char word[20];
    int count;
} WordCount;

int main() {
    char str[100];
    WordCount wordList[50]; // 假设最多存在50个不同单词
    int uniqueWords = 0;
    char *token;

    // 输入字符串(用fgets替代gets,避免缓冲区溢出)
    printf("Enter the String: ");
    fgets(str, sizeof(str), stdin);
    
    // 移除fgets读取到的末尾换行符
    str[strcspn(str, "\n")] = '\0';

    // 按空格拆分字符串提取单个单词
    token = strtok(str, " ");
    while (token != NULL) {
        // 跳过空字符串(处理连续空格的情况)
        if (strlen(token) == 0) {
            token = strtok(NULL, " ");
            continue;
        }

        // 检查当前单词是否已在统计列表中
        int found = 0;
        for (int i = 0; i < uniqueWords; i++) {
            if (strcmp(wordList[i].word, token) == 0) {
                wordList[i].count++;
                found = 1;
                break;
            }
        }

        // 若未找到则新增单词条目
        if (!found) {
            strcpy(wordList[uniqueWords].word, token);
            wordList[uniqueWords].count = 1;
            uniqueWords++;
        }

        token = strtok(NULL, " ");
    }

    // 输出最终统计结果
    printf("\n统计结果:");
    for (int i = 0; i < uniqueWords; i++) {
        printf("%s - %d", wordList[i].word, wordList[i].count);
        if (i != uniqueWords - 1) {
            printf(", ");
        }
    }

    return 0;
}

核心逻辑说明

  • 结构体WordCount:统一存储单词文本和对应的出现次数,方便批量管理。
  • fgets()替代gets():gets()存在缓冲区溢出风险,fgets()更安全,搭配strcspn()清除输入末尾的换行符。
  • strtok()拆分单词:以空格为分隔符拆分输入字符串,逐个提取独立单词,同时兼容连续空格的场景。
  • 查重与计数更新:遍历已统计的单词列表,找到重复项则累加计数,未找到则新增条目。

测试示例

输入:hello hello hello bye bye
输出:统计结果:hello - 3, bye - 2

内容的提问来源于stack exchange,提问作者emblox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 11:15:21