用c语言实现读取文件news.txt中出现次数前五的字母,并排序
时间: 2024-02-18 08:59:33 浏览: 156
以下是使用C语言实现读取文件中出现次数前五的字母,并按照出现次数从大到小排序的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1000
struct Count {
char c;
int count;
};
int compare(const void* a, const void* b) {
struct Count* c1 = (struct Count*)a;
struct Count* c2 = (struct Count*)b;
return c2->count - c1->count;
}
int main() {
FILE* fp;
char buffer[MAX_SIZE];
int count[26] = {0};
int i, j, len;
struct Count ans[26];
fp = fopen("news.txt", "r");
if (fp == NULL) {
printf("File open failed.\n");
return -1;
}
while (fgets(buffer, MAX_SIZE, fp) != NULL) {
len = strlen(buffer);
for (i = 0; i < len; i++) {
if (buffer[i] >= 'a' && buffer[i] <= 'z') {
count[buffer[i] - 'a']++;
} else if (buffer[i] >= 'A' && buffer[i] <= 'Z') {
count[buffer[i] - 'A']++;
}
}
}
fclose(fp);
for (i = 0; i < 26; i++) {
ans[i].c = 'a' + i;
ans[i].count = count[i];
}
qsort(ans, 26, sizeof(struct Count), compare);
printf("出现次数前五的字母及其出现次数为:\n");
for (i = 0; i < 5; i++) {
printf("%c: %d\n", ans[i].c, ans[i].count);
}
return 0;
}
```
该程序使用了一个长度为 26 的数组 `count` 来统计每个字母出现的次数,然后将结果存入结构体数组 `ans` 中,再使用 `qsort` 函数按照出现次数从大到小排序。最后输出出现次数前五的字母及其出现次数。注意需要将字母转换为小写字母再统计。
阅读全文