用 c 语言写以下题目:输入一个可能含空格的字符串(其长度不超过81),分别统计其中26个英文字母出现的次数(不区分大、小写字母),并按字母出现的次数,从高到低进行排序。若次数相同,按字母顺序排列。字母输出格式举例,例如:A-3,表示字母A出现3次,C-0表示字母C没有出现过,各字母输出之间用一个空格字符进行分隔。
时间: 2024-03-26 12:35:11 浏览: 88
以下是用C语言实现的代码:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_LEN 81
struct CharCount {
char ch;
int count;
};
int main() {
char str[MAX_LEN];
int i, j;
// 读入字符串
printf("请输入字符串(长度不超过81):\n");
fgets(str, MAX_LEN, stdin);
str[strcspn(str, "\n")] = '\0';
// 统计字母出现次数
struct CharCount count[26];
for (i = 0; i < 26; i++) {
count[i].ch = 'A' + i;
count[i].count = 0;
}
for (i = 0; i < strlen(str); i++) {
if (isalpha(str[i])) {
int index = toupper(str[i]) - 'A';
count[index].count++;
}
}
// 按照出现次数从高到低排序
for (i = 0; i < 26; i++) {
for (j = i + 1; j < 26; j++) {
if (count[i].count < count[j].count ||
(count[i].count == count[j].count &&
count[i].ch > count[j].ch)) {
struct CharCount temp = count[i];
count[i] = count[j];
count[j] = temp;
}
}
}
// 输出字母出现次数
for (i = 0; i < 26; i++) {
printf("%c-%d ", count[i].ch, count[i].count);
}
printf("\n");
return 0;
}
```
代码思路如下:
1. 读入字符串。
2. 统计字符串中每个字母出现的次数,保存到结构体数组 `count` 中。
3. 对 `count` 数组按照出现次数从高到低排序,如果出现次数相同则按照字母顺序排列。
4. 输出字母出现次数。
阅读全文
相关推荐


















