一个利用map统计一段英文文章中每个单词出现次数的小程序

#include <fstream>
#include <string>
#include <map>
using namespace std;

int main()
{
    map<string, int> m;
    ifstream ifs("calculate.txt");
    if(!ifs)
        return -1;
   
    string str("abcdefghigklmnopqrstuvwxyz");
    int i = 0;
    while(!ifs.eof())
    {
        char c,b;

       // 此处不可以使用输入流ifs>>c,因为输入流不读如空格。
        c = ifs.get();
        b = tolower(c);   
        if('a' <= b && b<= 'z')
        {
            str[i] = b;
            i++;
        }
        else
        {   
            string tmp;
            tmp = str.substr(0,i);
            ++m[tmp];
            i = 0;
        }   
    }
   
    string str1;
    while(cin>>str1)
    {
        cout<<str1<<"在文章中出现的次数是:";
        cout<<m[str1]<<endl;
    }
    return 0;
};

上述程序的map采用下标存取,若某单词不在文章中的时候,会自动添加一个键是该单词的元素,并把其值初始化为0.

克服此缺点采用如下程序:

#include <fstream>
#include <string>
#include <map>
using namespace std;

int main()
{
    map<string, int> m;
    ifstream ifs("calculate.txt");
    if(!ifs)
        return -1;
   
    string str("abcdefghigklmnopqrstuvwxyz");
    int i = 0;
    while(!ifs.eof())
    {
        char c,b;
        c = ifs.get();  // 此处不可以使用输入流ifs>>c,因为输入流不读如空格。
        b = tolower(c);   
        if('a' <= b && b<= 'z')
        {
            str[i] = b;
            i++;
        }
        else
        {   
            string tmp;
            tmp = str.substr(0,i);
            if(!m.count(tmp))
                m.insert(make_pair(tmp,1));
            else
                m[tmp]++;
            i = 0;
        }   
    }
   
    string str1;
    while(cin>>str1)
    {
        if(m.count(str1) == 0)
            cout<<str1<<"在文章中出现的次数是0."<<endl;
        else
            cout<<str1<<"在文章中出现的次数是"<<m[str1]<<endl;
    }
    return 0;
};

2009/2/11 by hekex1n@126.com

原文地址:https://www.cnblogs.com/kex1n/p/2286591.html