1. (简答题) Write a program to count the occurrences of each letter in an array of characters. Here is a sample run. ------------------------------------------------------ Enter the string : abcddcabae a occurs 3 times in the string, b occurs 2 times in the string, c occurs 2 times in the string, d occurs 2 times in the string, e occurs 1 times in the string,
时间: 2023-08-15 22:21:02 浏览: 134
以下是 C 语言代码实现,可以用来统计一个字符数组中每个字符的出现次数:
```c
#include <stdio.h>
#include <string.h>
void count_occurrences(char string[]) {
int freq[26] = {0}; // 初始化每个字母的出现次数为 0
for (int i = 0; i < strlen(string); i++) {
char c = string[i];
if (c >= 'a' && c <= 'z') {
freq[c - 'a']++; // 如果是小写字母,增加对应字母的出现次数
} else if (c >= 'A' && c <= 'Z') {
freq[c - 'A']++; // 如果是大写字母,增加对应字母的出现次数
}
}
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
printf("%c occurs %d times in the string.\n", 'a' + i, freq[i]);
}
}
}
int main() {
char string[100];
printf("Enter the string: ");
fgets(string, 100, stdin); // 从标准输入中读取字符串
count_occurrences(string);
return 0;
}
```
运行结果:
```
Enter the string: abcddcabae
a occurs 3 times in the string.
b occurs 2 times in the string.
c occurs 2 times in the string.
d occurs 2 times in the string.
e occurs 1 times in the string.
```
阅读全文