一、要点
1、使用map<string, int>统计词的出现次数,然后取最值;
2、注意cctype库中很多使用函数,如:isalnum()为字母数字、isdigit()为数字、isalpha()为字母、isupper()为大写字母、islower()为小写字母、toupper()转为大写字母、tolower()转为小写字母等等。
3、读入单词部分:
while( ( c = getchar() ) != '\n' )
if( isalnum(c) )
str += tolower(c);
else if( str.size() )//可能有连续多个非字母数字字符
{
++cnt[str];
str.clear();
}
if( str.size() )//统计最后一个单词;
++cnt[str];
4、测试点4答案错误:注意是否读入’\n’后还有一个词未统计。
二、代码
#include <cstdio>
#include <map>
#include <string>
#include <cctype>
using namespace std;
int main()
{
map<string, int> cnt;
char c;
string str;
while( (c = getchar()) != '\n' )
if( isalnum(c) )
str += tolower(c);
else if( str.size() )
{
++cnt[str];
str.clear();
}
if( str.size() )
++cnt[str];
map<string, int>::iterator ans = cnt.begin();
for( map<string, int>::iterator it = cnt.begin(); it != cnt.end(); ++it )
if( it->second > ans->second )
ans = it;
printf("%s %d", ans->first.c_str(), ans->second);
}