c语言输入一段字符串,输出字符串中出现次数最多的单词

c语言输入一段字符串,输出字符串中出现次数最多的单词

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

#define MAX_STR_LEN 1000
#define MAX_WORD_LEN 50

// 函数原型声明
void findMaxRepeatedWord(char *str);

int main() {
    char str[MAX_STR_LEN];

    // 输入字符串
    printf("请输入一段字符串: ");
    fgets(str, MAX_STR_LEN, stdin);
    str[strcspn(str, "\n")] = 0; // 移除换行符

    // 查找并输出出现次数最多的单词
    findMaxRepeatedWord(str);

    return 0;
}

void findMaxRepeatedWord(char *str) {
    char word[MAX_WORD_LEN];
    int wordCount[MAX_WORD_LEN] = {0}; // 存储每个单词出现的次数
    int maxCount = 0; // 最多出现次数
    char maxWord[MAX_WORD_LEN] = {0}; // 最多出现的单词
    int index = 0; // 单词索引

    // 分割字符串并统计单词出现次数
    char *token = strtok(str, " ");
    while (token != NULL) {
        // 清理单词,移除标点符号
        int len = strlen(token);
        for (int i = 0; i < len; ++i) {
            if (ispunct(token[i])) {
                memmove(&token[i], &token[i + 1], len - i);
                --len;
                --i;
            }
        }
        token[len] = '\0'; // 确保字符串结尾

        // 检查单词是否已经在数组中
        int found = 0;
        for (int i = 0; i < index; ++i) {
            if (strcmp(word + i * MAX_WORD_LEN, token) == 0) {
                wordCount[i]++;
                found = 1;
                break;
            }
        }
        // 如果是新单词,添加到数组中
        if (!found) {
            strcpy(word + index * MAX_WORD_LEN, token);
            wordCount[index] = 1;
            index++;
        }

        // 更新出现次数最多的单词
        for (int i = 0; i < index; ++i) {
            if (wordCount[i] > maxCount) {
                maxCount = wordCount[i];
                strcpy(maxWord, word + i * MAX_WORD_LEN);
            }
        }

        // 获取下一个单词
        token = strtok(NULL, " ");
    }

    // 输出结果
    if (maxCount > 1) {
        printf("出现次数最多的单词是: '%s',出现了 %d 次。\n", maxWord, maxCount);
    } else if (maxCount == 1) {
        printf("所有单词只出现了一次。\n");
    } else {
        printf("没有输入任何单词。\n");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值