#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

相关文章:

  • 2021-12-26
  • 2021-10-17
  • 2022-12-23
  • 2021-05-23
  • 2022-12-23
  • 2022-03-07
  • 2021-08-25
  • 2021-05-11
猜你喜欢
  • 2022-12-23
  • 2021-07-20
  • 2022-12-23
  • 2021-11-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案