C语言单词检索和统计程序
以下是一个简单的C语言单词检索和统计程序的示例:
#include <stdio.h>
#include <string.h>
#define MAX_WORDS 1000
#define MAX_WORD_LEN 30
int main() {
char text[1000];
char words[MAX_WORDS][MAX_WORD_LEN];
int freq[MAX_WORDS] = {0};
int num_words = 0;
printf("Enter text: ");
fgets(text, sizeof(text), stdin);
char *token = strtok(text, " \t\n");
while (token != NULL) {
int i, found = 0;
// Check if word is already in array
for (i = 0; i < num_words; i++) {
if (strcmp(token, words[i]) == 0) {
freq[i]++;
found = 1;
break;
}
}
// Add word to array if not found
if (!found) {
strcpy(words[num_words], token);
freq[num_words]++;
num_words++;
}
token = strtok(NULL, " \t\n");
}
printf("\nWord frequencies:\n");
for (int i = 0; i < num_words; i++) {
printf("%s: %d\n", words[i], freq[i]);
}
return 0;
}
该程序从标准输入中读取一行文本,将其分解为单词并统计每个单词出现的频率。它使用一个字符串数组来存储单词,一个整数数组来存储每个单词的出现次数,并使用strtok函数来分解输入文本。程序输出每个单词和其出现的次数。
原文地址: https://www.cveoy.top/t/topic/bMmc 著作权归作者所有。请勿转载和采集!