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");
}
}