用C语言编写程序,读入一行字符(长度小于1000),从中找出出现频率最高的字母(大小写算不同字母)出现的次数并输出。
时间: 2023-05-21 15:03:41 浏览: 136
可以使用一个大小为 52 的数组来记录每个字母出现的次数,其中前 26 个元素记录小写字母出现的次数,后 26 个元素记录大写字母出现的次数。遍历输入的字符串,对于每个字母,将其对应的计数器加一。最后再遍历一遍数组,找到出现次数最多的字母即可。
以下是示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[1001];
int count[52] = {0}; // 记录每个字母出现的次数
int max_count = 0; // 出现次数最多的字母的出现次数
char max_char; // 出现次数最多的字母
printf("请输入一行字符:\n");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 只考虑字母
int index = islower(str[i]) ? str[i] - 'a' : str[i] - 'A' + 26;
count[index]++;
if (count[index] > max_count) {
max_count = count[index];
max_char = str[i];
}
}
}
printf("出现频率最高的字母是 %c,出现了 %d 次。\n", max_char, max_count);
return 0;
}
```
注意,这个程序只考虑了 ASCII 码中的字母,如果要支持 Unicode 字符集,需要使用更复杂的方法来统计字符出现次数。
阅读全文
相关推荐
















