从终端输入一串字符,统计字符串中每个字母出现的次数。
提示:
用一个26个元素的数组,如num[26], 表示计数。num[0]存放a的个数, num[1]存放b的个数…。这样对每一个字符不必用switch,而只需用一个简单的计算:
++num[toupper(ch) - ’A’]就可以了。
从终端输入一串字符,统计字符串中每个字母出现的次数。
提示:
用一个26个元素的数组,如num[26], 表示计数。num[0]存放a的个数, num[1]存放b的个数…。这样对每一个字符不必用switch,而只需用一个简单的计算:
++num[toupper(ch) - ’A’]就可以了。
解答如下,回车键结束输入
#include <stdio.h>
#include <ctype.h>
int main()
{
int num[26]={0};
char ch=' ';
while((ch=getwchar())!='\n')
{
++num[toupper(ch) - 'A'];
}
for(int i=0;i<26 ;i++ )
{
printf("%c %d\n",i+'A',num[i]);
}
return 0;
}