求字符串中出现次数最多的字符

map这个东西还是挺好用的啊。以前都不怎么熟悉,应该看一下的。

#include <iostream>
#include <map>
#include <string>
 
using namespace std;
 
int main()
{
        string s = "cceuiwbmmmmabbddeeemmmmeeeff";
        map<char,int> chcount;
        for(map<char,int>::size_type i=0;i<s.size();i++)
        {
                chcount[s[i]]++;
        }
        char maxChar = chcount.begin()->first;
        for(map<char,int>::iterator pos=chcount.begin();pos!=chcount.end();++pos)
        {
                if(pos->second > chcount[maxChar])
                {
                        maxChar = pos->first;
                }
        }
 
        cout<<"The character which occures the most times is "<<maxChar<<" "<<endl;
        cout<<"It's times is "<<chcount[maxChar]<<endl;
        return 0;
}
posted @ 2011-10-03 13:45  ismy  阅读(197)  评论(0)    收藏  举报