计算字符串每个字符次数c语言
时间: 2024-01-04 18:51:56 浏览: 25
可以使用一个数组来记录每个字符出现的次数,具体实现如下:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int main() {
char str[MAX_LEN];
int count[256] = {0}; // 初始化每个字符出现次数为0
printf("输入字符串:");
fgets(str, MAX_LEN, stdin);
int len = strlen(str);
for (int i = 0; i < len; i++) {
count[(int)str[i]]++;
}
printf("每个字符出现的次数:\n");
for (int i = 0; i < 256; i++) {
if (count[i] > 0) {
printf("%c : %d\n", i, count[i]);
}
}
return 0;
}
```
在上面的程序中,我们定义了一个数组 `count` 用来记录每个字符出现的次数,数组的下标是字符的 ASCII 码值,初始化为0。
输入字符串时使用 `fgets` 函数,因为它可以避免缓冲区溢出的问题。然后遍历字符串中的每个字符,将其在 `count` 数组中对应的元素加1。
最后,遍历一遍 `count` 数组,输出每个字符及其出现次数。注意,只有出现次数大于0的字符才需要输出。