c语言编写函数 统计给定字符串中各个字母出现的次数 不区分大小写
时间: 2023-11-11 19:03:35 浏览: 47
可以使用一个长度为26的整型数组来统计每个字母出现的次数,同时将所有的字母转换为小写字母进行统计。具体实现如下:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void count_letters(char* str, int* count) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
char c = tolower(str[i]);
if (c >= 'a' && c <= 'z') {
count[c - 'a']++;
}
}
}
int main() {
char str[] = "Hello, world!";
int count[26] = {0};
count_letters(str, count);
for (int i = 0; i < 26; i++) {
printf("%c: %d\n", 'a' + i, count[i]);
}
return 0;
}
```
在这个例子中,`count_letters()` 函数接受一个字符串和一个整型数组,统计字符串中每个字母出现的次数,并将结果存储在整型数组中。`main()` 函数定义了一个字符串和一个长度为26的整型数组,然后调用 `count_letters()` 函数来统计字符串中每个字母出现的次数。最后,使用 `printf()` 函数输出结果。