如何统计并显示给定字符串中每个字符出现的次数?C语言程序设计
时间: 2025-02-24 22:41:54 浏览: 75
在C语言中,你可以使用数组或哈希表(如`struct`或`unordered_map`)来统计字符串中每个字符出现的次数。这里是一个简单的示例,我们将使用数组来存储字符及其计数:
```c
#include <stdio.h>
#include <string.h>
#define MAX_CHAR 256
void count_chars(char* str) {
int char_count[MAX_CHAR] = {0}; // 初始化所有字符计数为0
for (int i = 0; str[i]; ++i) {
char_count[str[i]]++; // 对每个字符加一
}
for (int i = 0; i < MAX_CHAR; ++i) {
if (char_count[i]) {
printf("字符 '%c' 出现了 %d 次\n", i, char_count[i]);
}
}
}
int main() {
char input[100];
printf("请输入一个字符串: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0'; // 去除fgets获取的换行符
count_chars(input);
return 0;
}
```
在这个程序中,我们遍历输入的字符串,每次遇到一个字符就增加相应位置在`char_count`数组的计数。然后再次遍历数组,打印出非零计数的字符及其出现次数。
阅读全文
相关推荐

















