c语言统计单词频率
时间: 2023-07-02 19:10:43 浏览: 205
以下是使用C语言统计单词频率的示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_WORD_LEN 50 // 最大单词长度
#define MAX_WORDS 1000 // 最多单词数
int main()
{
char text[MAX_WORDS][MAX_WORD_LEN];
int count[MAX_WORDS] = {0};
int num_words = 0;
// 从标准输入读入文本,以空格、换行符、制表符作为分隔符
char delim[] = " \n\t";
char *word = strtok(gets(text[0]), delim);
while (word != NULL && num_words < MAX_WORDS)
{
strcpy(text[num_words], word);
num_words++;
word = strtok(NULL, delim);
}
// 统计每个单词出现的次数
for (int i = 0; i < num_words; i++)
{
count[i]++; // 先加上自己出现的一次
for (int j = i + 1; j < num_words; j++)
{
if (strcmp(text[i], text[j]) == 0)
{
count[i]++;
count[j] = -1; // 标记已经统计过了,避免重复计数
}
}
}
// 输出单词及其出现次数
printf("Word\tFrequency\n");
for (int i = 0; i < num_words; i++)
{
if (count[i] > 0)
{
printf("%s\t%d\n", text[i], count[i]);
}
}
return 0;
}
```
该程序从标准输入读入文本,使用空格、换行符、制表符作为分隔符,将文本中的每个单词存储到一个字符串数组中,并逐个统计每个单词出现的次数。最后输出每个单词及其出现次数。注意,该程序只能处理包含不超过1000个单词、每个单词不超过50个字符的文本。如果需要处理更大的文本,需要根据实际情况修改程序。
阅读全文
相关推荐
















