c语言找出字符串中出现次数最少的字符,出现了多少次
时间: 2023-11-28 07:04:46 浏览: 228
以下是一个例子,输入一个字符串,输出出现次数最少的字符以及出现次数:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int count[256] = {0}; // 用一个数组记录每个字符出现的次数,ASCII 码共有 256 个字符
printf("Please input a string: ");
fgets(str, 100, stdin);
int len = strlen(str);
for (int i = 0; i < len; i++) {
count[str[i]]++; // 统计每个字符出现的次数
}
int minCount = len; // 初始化为字符串长度,因为最多出现 len 次
char minChar;
for (int i = 0; i < 256; i++) {
if (count[i] != 0 && count[i] < minCount) { // 如果出现次数不为 0 且比当前最小值小
minCount = count[i];
minChar = i;
}
}
printf("The character that appears least often is '%c', which appears %d times.\n", minChar, minCount);
return 0;
}
```
示例输出:
```
Please input a string: hello world
The character that appears least often is 'd', which appears 1 times.
```
阅读全文