请编写程序,找出一段给定文字中出现最频繁的那个英文字母。
This is a simple TEST. There ARE numbers and other symbols 1&2&3...........
输出样例:
e 7
解:首先字符串里有空格,要用getline()输入,其次需要将字符串中的大写字母转换为小写字母,
然后还是桶排序的思想,遍历到小写字母,就将其个数加一,
但是字母就26个,小写字母'a' - 'z'减去'a' 就刚好对应0-25; 所以我们可以让0-25的下标去计数就可以了,会比去用字母的ascii码方便很多 ;
最后遍历26个字母的下标,比较出最大值, i+‘a’即是对应的字母;注意,由于是从小到大找出的最大次数,因此输出的字母就是字母序最小的字母。
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int main(){
string s;
getline(cin,s);
int cnt[27]={0};
for(int i=0;i<s.length();i++){
//s[i]=tolower(s[i]); //转换为小写字母
if(s[i]>='A'&&s[i]<='Z')
s[i]=s[i]-'A'+'a';
//if(islower(s[i])) cnt[s[i]-'a']++; //判断,如果是小写字母,执行
if(s[i]>='a'&&s[i]<='z') cnt[s[i]-'a']++;
}
int max=cnt[0],t;
for(int i=1;i<26;i++){
if(cnt[i]>max){
max=cnt[i];
t=i;
}
}
printf("%c %d", t+'a', max);
return 0;
}