从键盘输入一字符串,统计输入字符出现的次数,将统计结果输出,输出格式如示例所示。运行示例:
请输入字符串strings
strings
输入需要分析的字符s
字符s在字符串strings中出现的次数为:2
#include <string.h>
int main() {
char str[100], ch;
int i = 0, count = 0;
printf("请输入字符串:");
fgets(str, sizeof(str), stdin);
printf("输入需要分析的字符:");
scanf("%c", &ch);
while (str[i] != '\0') {
if (str[i] == ch) {
count++;
}
i++;
}
printf("字符%c在字符串%s中出现的次数为:%d\n", ch, str, count);
return 0;
}
解答示范:
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
printf("请输入一个字符串:\n");
scanf("%[^\n]", str); // 读取输入字符串,不包括换行符
int count_table[256] = {0}; // 统计字符数的数组,初始值为0
int len = strlen(str); // 获取字符串长度
// 遍历字符串,对每个字符的出现次数加1
for(int i = 0; i < len; i++)
{
count_table[(int)str[i]]++;
}
// 输出每个字符及其出现次数
for(int i = 0; i < 256; i++)
{
if(count_table[i] > 0)
{
printf("%c: %d\n", (char)i, count_table[i]);
}
}
return 0;
}
首先读取用户输入的字符串,使用scanf
函数中的%[^\n]
格式化字符,可以读取整行字符串,不包括换行符。
然后定义一个长度为256的数组count_table
,即字符可能的种类数,初始值均为0。
遍历字符串,对于每个字符的ASCII码,在count_table
数组中对应下标的值加1,统计其出现次数。
最后遍历对应的数组,如果出现次数大于0,则输出字符和出现次数。注意要将下标转换为对应的字符显示,使用(char)i
。