C语言:如何按出现频率及ASCII值排序文件中的字母
C语言字母频率统计排序问题
我编写了一个用于统计文件中字母出现次数的C语言函数,但无法实现按出现频率排序的逻辑;要求按出现频率从高到低排序,当两个字母出现次数相同时,ASCII值更大的字母排在前面。
示例输入文件内容:Ovo je primjer znakovne datoteke
预期输出:EOAJKNRTVDIMPZ
当前代码输出:ADEIJKMNOPRTVZ
我尝试通过从数组末尾倒序遍历的方式实现排序,但未成功,相关尝试代码如下:
for (int i = 26; i > 0; count--) { for (int j = 26 - 1; i >= 0; i--) { if (occurrences[j] == i) { fprintf(output, "%c", j + 'A'); } } }
当前实现统计功能的完整C代码:
#include <stdio.h> #include <stdlib.h> #include <ctype.h> void process_input_file(const char* input_file, const char* output_file) { FILE* input = fopen(input_file, "r"); if (input == NULL) { perror("Error opening the input file"); exit(EXIT_FAILURE); } int occurrences[26] = {0}; int c; while ((c = fgetc(input)) != EOF) { if (isalpha(c)) { c = toupper(c); occurrences[c - 'A']++; } } fclose(input); FILE* output = fopen(output_file, "w"); if (output == NULL) { perror("Error opening the output file"); exit(EXIT_FAILURE); } for (int i = 0; i < 26; i++) { if (occurrences[i] > 0) { fprintf(output, "%c", i + 'A'); } } fclose(output); } int main() { char input_file[1000]; printf("Enter the name of the input file: "); scanf("%s", input_file); process_input_file(input_file, "statistics.txt"); return 0; }
解决方案
问题分析
原代码仅按A-Z顺序输出存在的字母,完全未处理排序逻辑。你尝试的倒序遍历代码存在循环变量混乱(count未定义、内层循环错误使用i作为终止条件)的问题,无法实现预期排序。
正确实现逻辑
要满足需求,我们可以:
- 先统计所有字母的出现次数,找到最大出现次数
- 从最大次数开始递减遍历每个可能的次数值
- 对每个次数值,从Z到A倒序遍历字母数组,确保频率相同时ASCII值大的字母优先输出
修改后的代码
替换原代码中输出部分的循环,完整修改后的函数如下:
#include <stdio.h> #include <stdlib.h> #include <ctype.h> void process_input_file(const char* input_file, const char* output_file) { FILE* input = fopen(input_file, "r"); if (input == NULL) { perror("Error opening the input file"); exit(EXIT_FAILURE); } int occurrences[26] = {0}; int c; while ((c = fgetc(input)) != EOF) { if (isalpha(c)) { c = toupper(c); occurrences[c - 'A']++; } } fclose(input); FILE* output = fopen(output_file, "w"); if (output == NULL) { perror("Error opening the output file"); exit(EXIT_FAILURE); } // 找到最大出现次数 int max_count = 0; for (int i = 0; i < 26; i++) { if (occurrences[i] > max_count) { max_count = occurrences[i]; } } // 按频率从高到低、同频率按ASCII降序输出 for (int count = max_count; count > 0; count--) { for (int j = 25; j >= 0; j--) { if (occurrences[j] == count) { fprintf(output, "%c", j + 'A'); } } } fclose(output); } int main() { char input_file[1000]; printf("Enter the name of the input file: "); scanf("%s", input_file); process_input_file(input_file, "statistics.txt"); return 0; }
效果验证
用示例输入测试,输出结果为EOAJKNRTVDIMPZ,完全符合预期要求。
内容的提问来源于stack exchange,提问作者eminbihh
相关产品推荐
相关产品推荐

