一开始我是想逐个查找单词,每次用string.find()方法,一边计数一边删除,直到原串为空,但是最后发现一个异常致命的错误,find并不是全词匹配,假如说识别出一个单词a,那么后面所有单词中的a就都被删除了。。。
最后还是得用map,一边识别单词,识别出一个就统计一个,而不是向后查找。但是还是会错一个。
推荐一版:https://blog.youkuaiyun.com/hy971216/article/details/81563094
#include<iostream>
#include<string>
#include<map>
using namespace std;
map<string,int> words;
map<string,int>::iterator it;
bool Isc( char c){
if(c>='a'&&c<='z'|| c>='0'&&c<='9')
return true;
return false;
}
int main(){
string s,word;
getline(cin,s);
int len=s.length(),i=0;
int st=0,l;
while(i<len){
if(s[i]>='A'&&s[i]<='Z')
s[i]=s[i]+32;
if(!Isc(s[i])){
i++;
continue;
}
st=i;
l=0;
while(Isc(s[i])){
i+=1;
l+=1;
}
word=s.substr(st,l);
//cout<<"word:"<<word<<"|| st:"<<st<<" l:"<<l<<" i:"<<i<<endl;
i+=1;
if(words.find(word)==words.end())
words[word]=1;
else
words[word]+=1;
}
int t=1;
for(it=words.begin();it!=words.end();it++){
if(it->second>t){
word=it->first;
t=it->second;
}
else if(it->second==t && it->first<word)
{
word=it->first;
t=it->second;
}
}
cout<<word<<" "<<words[word];
system("pause");
return 0;
}