用c语言统计一篇文章中每个单词出现的次数
时间: 2023-09-10 09:15:05 浏览: 80
以下是用C语言实现统计文章中每个单词出现次数的示例代码:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD_LENGTH 50
#define MAX_WORDS 1000
int main() {
char article[10000];
printf("请输入文章:\n");
fgets(article, 10000, stdin);
char words[MAX_WORDS][MAX_WORD_LENGTH];
int freq[MAX_WORDS] = {0};
int num_words = 0;
char *p_word = strtok(article, " ,.\n");
while (p_word != NULL && num_words < MAX_WORDS) {
strncpy(words[num_words], p_word, MAX_WORD_LENGTH);
words[num_words][MAX_WORD_LENGTH - 1] = '\0';
for (int i = 0; i < strlen(words[num_words]); i++) {
words[num_words][i] = tolower(words[num_words][i]);
}
freq[num_words]++;
num_words++;
p_word = strtok(NULL, " ,.\n");
while (p_word != NULL && strlen(p_word) == 1 && ispunct(p_word[0])) {
p_word = strtok(NULL, " ,.\n");
}
for (int i = 0; i < num_words - 1; i++) {
if (strcmp(words[i], words[num_words - 1]) == 0) {
freq[i]++;
num_words--;
}
}
}
printf("单词\t\t出现次数\n");
printf("=========================\n");
for (int i = 0; i < num_words; i++) {
printf("%-20s%d\n", words[i], freq[i]);
}
return 0;
}
```
该程序首先读入文章,然后将文章分解为单词。对于每个单词,程序将其转换为小写字母,并在单词列表中查找是否已经出现过。如果出现过,那么该单词的出现次数加1,否则将该单词添加到单词列表中。最后,程序输出每个单词及其出现次数。
阅读全文