代码如下:
#include<stdio.h>
int main()
{
int i=0, j;
int num[26] = { 0 };
char str[50];
printf("enter the lines:");
gets(str);
while (str[i] != 0)
{
if (str[i] >= 'a' && str[i] <= 'z')
{
num[str[i] - 'a']++;
//这样做可以让a对齐0,b对齐1.
}
i++;
}
for (i = 0; i < 26; i++)
{
if (num[i] != 0)
{
//与上面同理,这样可以让a,b,c逐一输出。
printf("%c的数量是:%d\n", i + 'a', num[i]);
}
}
return 0;
}
值得注意的是,这里为了使num可以在while循环中逐一使0对应a,1对应b,而采用num[str[i]-'a']
的形式。
同理,为了使最后输出%c能够逐一显示a,b,c等,使用了i+’a'的形式。
结果如下: