牛客网 单词识别题解

题目描述

输入一个英文句子,把句子中的单词(不区分大小写)按出现次数按从多到少把单词和次数在屏幕上输出来,要求能识别英文句号和逗号,即是说单词由空格、句号和逗号隔开。
 
我的题解:
#include <iostream>
#include <algorithm>
#include <sstream>
#include <map>
using namespace std;

class project{
public:
    void fun1(){
        string line,word;
        map<string, size_t> word_count;
        getline(cin,line);
        transform(line.begin(), line.end(), line.begin(), ::tolower);
        for(auto i=line.begin(); i!=line.end(); i++){
            if(*i==',' || *i=='.') *i=' ';
        }
        stringstream s(line);
        //line << lines;
        while(s >> word)
            ++word_count[word];
        for(const auto &w : word_count)
            cout << w.first << ":" << w.second << endl;
    }
    
};

int main()    
{
    project P;
    P.fun1();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/HonkerYblogs/p/10548749.html