作业帮 > 综合 > 作业

C语言统计文本字母出现次数按从大到小顺序排,急用高分

来源:学生作业帮 编辑:搜搜做题作业网作业帮 分类:综合作业 时间:2024/07/29 15:05:28
C语言统计文本字母出现次数按从大到小顺序排,急用高分
下面是做好可以导入文本,但是不能大小写归一按顺序排列
http://zhidao.baidu.com/link?url=22k-9jv5M4U5RPe5toDUbxd1iYfSSfp0QjPxKcPDo0lc3ZprlpYOOJ61RWigqQJ1GISp3NwHHT2U2wVWLagkTK
这是可以按顺序排的,但是需要手动输入,不能直接导入txt文本内容
http://zhidao.baidu.com/question/282930834.html?qbl=relate_question_2&word=%D7%D6%C4%B8%C6%B5%C2%CA%CD%B3%BC%C6%B9%A4%BE%DF
http://zhidao.baidu.com/link?url=Arq2HqxyR6Llya7DnSoZ4zX9EUjCWB3NWmkgIsNzE6Pv5tU7apabrLqGRPfYsv4MIONEoE1w30vC5_RrPPPGxa
C语言统计文本字母出现次数按从大到小顺序排,急用高分
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main() {
int counts[26], i;
char c;
FILE* fp = fopen("input.txt", "r");
FILE* op = fopen("output.txt", "w");
memset(counts, 0, sizeof(counts));
while (fscanf(fp, "%c", &c) == 1) {
if (isalpha(c)) {
counts[tolower(c) - 'a']++;
}
}
for (i = 0; i < 26; i++) {
printf("%c: %d\n", i + 'a', counts[i]);
fprintf(op, "%c: %d\n", i + 'a', counts[i]);
}
fclose(fp);
fclose(op);
}
再问: 没有导入文本内容
再答: 你需要把input.txt换成你想导入的文件的名称
把output.txt换成你想导出结果的文件的名称
再问: 我改了一下文件地址,数据出来了但是大小排序没有出来
再答: 你想出现次数多的排前面还是排后面,如果次数相同是接近a的排前面还是接近z的排前面?#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
\x09char c;
\x09int times;
}stat;

int cmp(const void* a, const void* b) {
\x09stat* sa = (stat*)a;
\x09stat* sb = (stat*)b;
\x09if (sa->times != sb->times) {
\x09\x09return sb->times - sa->times;
\x09}
\x09else {
\x09\x09return sa->c - sb->c;
\x09}
}

int main() {
\x09int i;
\x09char c;
\x09stat counts[26];
\x09FILE* fp = fopen("input.txt", "r");
\x09FILE* op = fopen("output.txt", "w");
\x09for (i = 0; i < 26; i++) {
\x09\x09counts[i].c = 'a' + i;
\x09\x09counts[i].times = 0;
\x09}
\x09while (fscanf(fp, "%c", &c) == 1) {
\x09\x09if (isalpha(c)) {
\x09\x09\x09counts[tolower(c) - 'a'].times++;
\x09\x09}
\x09}
\x09qsort(counts, 26, sizeof(stat), cmp);
\x09for (i = 0; i < 26; i++) {
\x09\x09printf("%c: %d\n", counts[i].c, counts[i].times);
\x09\x09fprintf(op, "%c: %d\n", counts[i].c, counts[i].times);
\x09}
\x09fclose(fp);
\x09fclose(op);
}