使用 map(点击查看详细用法) 统计单词出现次数。
代码:
#include<cstdio>
#include<string>
#include<map>
#include<iostream>
using namespace std;
string a;
bool isWord(int i){
if((a[i] >= '0' && a[i] <= '9') || (a[i] >= 'a' && a[i] <= 'z') || (a[i] >= 'A' && a[i] <= 'Z')){
return true;
}else return false;
}
int main(){
map<string,int> mp;
string temp;
getline(cin,a);
for(int i = 0;i < a.size();i++){
temp.clear();
if(isWord(i) == true){
while(isWord(i) == true){
if(a[i] >= 'A' && a[i] <= 'Z') a[i] += 32;
temp += a[i];
i++;
}
if(mp.find(temp) == mp.end()){
mp.erase(temp);
mp[temp] = 1;
}else{
mp[temp] += 1;
}
}
}
int min = -1;
map<string,int>::iterator ite;
for(map<string,int>::iterator it = mp.begin();it != mp.end();it++){
if(it->second > min){
min = it->second;
ite = it;
}
}
cout << ite->first << " " << ite->second;
return 0;
}