程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於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;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved