求一个文章每个字出现次数并且排序。要求简单一点。我是c语言初学者。
2条回答 默认 最新
关注 使用了一个固定大小的数组来存储字出现的次数,并使用冒泡排序对结果进行排序。你可以将文章内容替换为你想要统计的文章,然后编译并运行这段代码,即可得到每个字出现次数并排序的结果。请注意,由于使用了固定大小的数组,所以这个实现有一个最大字数的限制(在这个示例中为1000个字)。如果文章中的字数超过了这个限制,需要相应地调整数组大小。
#include <stdio.h> #include <string.h> #define MAX_WORD_LENGTH 100 #define MAX_WORDS 1000 typedef struct { char word[MAX_WORD_LENGTH]; int count; } WordCount; void countWords(char* article) { int articleLength = strlen(article); WordCount wordCounts[MAX_WORDS]; int wordCountSize = 0; // 初始化字出现次数为0 for (int i = 0; i < MAX_WORDS; i++) { wordCounts[i].count = 0; } // 统计每个字出现的次数 for (int i = 0; i < articleLength; i++) { char currentWord[MAX_WORD_LENGTH]; int currentWordLength = 0; while (i < articleLength && article[i] != ' ') { currentWord[currentWordLength++] = article[i++]; } currentWord[currentWordLength] = '\0'; // 在字出现次数数组中查找当前字 int found = 0; for (int j = 0; j < wordCountSize; j++) { if (strcmp(wordCounts[j].word, currentWord) == 0) { wordCounts[j].count++; found = 1; break; } } // 如果字出现次数数组中没有找到当前字,则添加到数组中 if (!found) { strcpy(wordCounts[wordCountSize].word, currentWord); wordCounts[wordCountSize].count = 1; wordCountSize++; } } // 使用冒泡排序对字出现次数进行排序 for (int i = 0; i < wordCountSize - 1; i++) { for (int j = 0; j < wordCountSize - i - 1; j++) { if (wordCounts[j].count < wordCounts[j + 1].count) { WordCount temp = wordCounts[j]; wordCounts[j] = wordCounts[j + 1]; wordCounts[j + 1] = temp; } } } // 输出结果 for (int i = 0; i < wordCountSize; i++) { printf("%s: %d\n", wordCounts[i].word, wordCounts[i].count); } } int main() { char article[] = "This is a sample article to demonstrate word count and sorting in C language"; countWords(article); return 0; }
解决 无用评论 打赏 举报
悬赏问题
- ¥15 求高通平台Softsim调试经验
- ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?
- ¥15 wpf ScrollViewer实现冻结左侧宽度w范围内的视图
- ¥15 栅极驱动低侧烧毁MOSFET
- ¥30 写segy数据时出错3
- ¥100 linux下qt运行QCefView demo报错
- ¥50 F1C100S下的红外解码IR_RX驱动问题
- ¥20 基于matlab的航迹融合 航迹关联 航迹插补
- ¥15 用Matlab实现图中的光线追迹
- ¥15 联想笔记本开机出现系统更新界面