C++ STL map A1071 Speech Patterns(25) (注意如何从字符串里 分割出单词,注意读取整行带空格的string 需要使用 getlint(cin,str) 函数)

#include <bits/stdc++.h>
#include<math.h>
#include <string>
using namespace std;
const int maxn = 40010;//最大学生人数
bool check(char c){
    if(c >= '0' && c<= '9') return true;
    if(c >= 'A' && c<= 'Z') return true;
    if(c >= 'a' && c<= 'z') return true;
    return false; 
}
int main(){
    map<string,int> count;//count计数字符串出现的次数
    string str;
    getline(cin,str);
    int i = 0;
    while(i < str.length()){
        string word;
        while(i < str.length() && check(str[i]) == true){//如果是单词的字符
            if(str[i] >= 'A' && str[i] <= 'Z'){
                str[i] += 32;//将大写字母转化为小写字母
            }
            word += str[i];
            i++;
        }
        if(word != ""){
            if(count.find(word) == count.end()){
                count[word]  = 1;
            }else{
                count[word]++;
            }
        }
        while(i < str.length() && check(str[i])==false){
            i++;
        }
    }
    string ans;//存放出现次数最多的单词
    int MAX = 0;
    for(map<string,int>::iterator it = count.begin();it != count.end();++it){
        if(it->second > MAX){
            MAX = it->second;
            ans = it->first;
        }
    }
    cout<<ans<<" "<<MAX<<endl;
    system("pause");
    return 0;
} 

猜你喜欢

转载自www.cnblogs.com/JasonPeng1/p/12203521.html