利用c语言输入一串英文,统计并输出字母出现的次数
时间: 2023-12-19 16:07:24 浏览: 31
```c
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[1000];
int count[26] = {0}; // 用数组记录每个字母出现的次数
printf("请输入一串英文:");
fgets(str, 1000, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 判断是否为字母
count[tolower(str[i]) - 'a']++; // 统计字母出现的次数
}
}
printf("字母出现的次数为:\n");
for (int i = 0; i < 26; i++) {
printf("%c: %d\n", 'a' + i, count[i]);
}
return 0;
}
```
这段代码中,我们首先定义了一个字符串数组 `str` 用于存储输入的英文字符串,以及一个整型数组 `count` 用于记录每个字母出现的次数。数组 `count` 的长度为 26,表示英文字母的个数。
接着,我们使用 `fgets()` 函数从用户输入中读取字符串,并逐个字符进行遍历。在遍历过程中,我们使用 `isalpha()` 函数判断当前字符是否为字母,若是,则使用 `tolower()` 函数将其转换为小写字母,并将其在 `count` 数组中对应位置的值加 1。
最后,我们使用一个循环遍历 `count` 数组,输出每个字母出现的次数。其中,`'a' + i` 表示当前字母的字符编码,`count[i]` 表示当前字母出现的次数。