使用C语言实现一段代码满足以下要求:
当输入一段字符串以后,可以输出不同字母的个数,如输入aaaggg,则输出3a3g
直接给出代码:
#include <stdio.h>
#include <stdlib.h>
void letter_count(char *str,int cnt[])
{
int i = 0;
while(str[i])//the last char in str is '\0'
{
cnt[str[i] - 'a'] += 1;//字符类型只能用''包围
i++; //计数每个字母的个数
}
}
int main()
{
char str[128];
int cnt[26] = {};//0 to 25 mapping a to z
printf("str:");
scanf("%s",str);
letter_count(str,cnt);
for(int i = 0; i < 26; i++)
{
if(cnt[i] != 0)
printf("%d%c",cnt[i],'a'+ i);
}
printf("\n");
system("pause");
return 0;
}
结果测试