统计字符串中出现次数最多的字母及其出现次数C++

小弱鸡看不太懂别人的代码,于是用了结构体的方法,将字母及其出现次数打包!

#include <iostream>
#include <string.h>
#include <algorithm> 
using namespace std;
typedef struct
	{string ch;
	int total;
	}sum;
bool cmp1(sum a,sum b){
	return a.total>b.total;
}
int main()
{
	string str;
	
	
	getline(cin,str);
	int len=str.length();
	sum s[50];
	for(int i=0;i<len;i++)
	{
		int count=0;
		for(int j=0;j<len;j++)
		{
			if(str[i]==str[j])
			{
				++count;
			}
			
		}
		s[i].ch=str[i];
		s[i].total=count;
	}
	sort(s,s+len,cmp1);
	cout<<s[1].total<<"  "<<s[1].ch<<endl;
	
	return 0;
	
}
} 

猜你喜欢

转载自blog.csdn.net/qq_37181805/article/details/88420279