思路
- 1.分词,用
char[]
储存输入数据,gets(a)
输入一行数据,s=s+a(i)//(string 的性质)
划分并组合成单词。 - 2.统计,用
map<string,int>
统计数据即可。
自己出错的地方
- 1.
char a[]
是用gets(a)
输入,不是cin>>a
,是用strlen(a)
统计长度不是用sizeof(a)
。 - 2.用
isalnum
判断是否为字母或者数字,tolower
将大写变为小写。 - 3.
mp[s]
初始值为0。 - 4.
map<string, int>::iterator it;
可以用it->second
或者it->first
找出值。
代码
#include <stdio.h>
#include<iostream>
#include <map>
#include <ctype.h>
#include <string>
#include <string.h>
#include <sstream>
using namespace std;
map<string, int> mp;
char a[1048576];
int main()
{
gets_s(a);
int l = strlen(a);
string s;
int i = 0;
while (i<l)
{
while (!isalnum(a[i]) && i<l)
{
i++;
}
s = "";
while (isalnum(a[i])&&i<l)
{
s += tolower(a[i]);
i++;
}
mp[s]++;
}
int max = -1;
string out;
map<string, int>::iterator it;
it = mp.begin();
for (; it != mp.end(); it++)
{
if (it->second>max)
{
max = it->second;
out = it->first;
}
}
cout << out <<" "<< max << endl;
return 0;
}