当前位置:编程学习 > C/C++ >>

单词统计

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <set>
#include <map>


using namespace std;


class CWord
{
    string word;
public:
    CWord(string word)
    {
        this->word = word;
    }
    string GetWord()const{return word;}
    bool operator<(const CWord&w)const{//用于添加集合
        return word < w.GetWord();
    }
    bool operator ==(const string &s)const{//用于查询
        return word == s;
    }
};


class CWordSet
{
    set<CWord> wordSet;
public:
    bool AddString(string s)
    {
        wordSet.insert(CWord(s));
        return true;
    }
    void show(ostream &os)
    {
        set<CWord>::iterator it = wordSet.begin();
        while(it!=wordSet.end())
        {
            os<<(*it).GetWord()<<"\t";
            it++;
        }
    }
};


class CWordMap
{
    map<CWord,int>wordMap;
public:
    bool AddString(string s)
    {
        map<CWord,int>::iterator it = wordMap.find(s);
        if(it == wordMap.end())
        {
            pair<CWord,int>p(CWord(s),1);
            wordMap.insert(p);
        }
        else{
            (*it).second+=1;
        }
        return true;
    }


    void Show(ostream &os)
    {
        map<CWord,int>::iterator it = wordMap.begin();
        while(it!=wordMap.end())
        {
            string ss = ((*it).first).GetWord();
            int n = (*it).second;
            os<<ss<<"\t"<<n<<endl;
            it++;
        }
    }
};


int main()
{
    CWordSet wordSet;
    CWordMap wordMap;


    int pos = 0;
    string s = "";
    string delimset = ",.";
    ifstream in("a.txt");
    while(!in.eof())
    {
        getline(in,s);
        if(s=="")
        {
            continue;
        }
        pos = 0;
        while((pos=s.find_first_of(delimset,pos))!=string::npos)
        {
            s.replace(pos,1," ");
        }
        istringstream stringeam(s);
        while(!stringeam.eof())
        {
            stringeam>>s;
            if(s=="")
                continue;
            wordSet.AddString(s);
            wordMap.AddString(s);
        }
    }
    in.close();
    cout<<"单词集合为"<<endl;
    wordSet.show(cout);
    cout<<endl;
    cout<<"单词及出现次数"<<endl;
    wordMap.Show(cout);
    cout<<endl;
    return 0;
}

补充:软件开发 , C语言 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,