For beginners, when you see this type of string statistics question, you will first think of if selection statement.
Do a good range of conditions such as: ('a'<=str[i])&&(str[i]<='z')
like this It is done to classify the input string. But the subsequent statistics on the specific number of occurrences of each letter in the string are helpless. (For example, I decided at the beginning that if I choose to determine the 26 letters to be counted one by one, and later I will write the case where the number is 0, which is too complicated)
At this time, a specific algorithm is required.
Drawing lessons from the code of other programmers, noticed that the subsequent letters can be expressed through the corresponding expressions.
Code display:
#include<stdio.h>
#include<string.h>
#define N 100//宏定义便于定义字符数组的宽度
int main()
{
int cnt[26]={
0},len,i,j;
char str[N];//宏定义
printf("请输入一个字符串!\n");
gets(str);
len=strlen(str);//strlen剔除'\0'
for(i=0;i<len;i++)
{
for(j=0;j<26;j++)//26个字母
{
if(str[i]=='a'+j)//此处就是一个表达式,'z'与'a'相差26,在'a'上特定加上数字即可表示相应字母
{
cnt[j]++;//这样解决了特定字母出现个数特定数组下标统计。
break;//内循环一个判定完之后暂停。等待外循环的下一个字符。
}
}
}
printf("统计结果为:\n");
for(i=0;i<26;i++)
{
if(cnt[i]!=0)
{
printf("%c:%d\n",i+'a',cnt[i]);//此处的i+'a'较str[i]更好,若是str[i]还得一一判定是否为字母,且i是记录了输入字符串中有哪些字母,在'a'之上相加个数即可表示。
}
}
return 0;
}
The code analysis is detailed in the code.