计算一段字符串中单词的个数

来源:互联网 发布:windows live 软件包 编辑:程序博客网 时间:2024/04/30 07:16
#include<iostream>#include<fstream>#include <string>#include <map>using namespace std;void CountWords(){//ifstream is("/*打开输入文件*/");//ofstream os("/*打开输出文件*/");map<string,int> mp;map<string,int>::iterator it;string str;getline(cin,str);int j=0;int len=str.length();for (int i=0;i<len;i++){if (str[i]==' '||i==len-1){if (i==len-1){i++;}string tmp=str.substr(j,i-j);mp[tmp]++;j=i+1;}}while(cin>>str){if(str =="EOF")break;++mp[str];}for(it=mp.begin();it!=mp.end();it++) //遍历      {          cout<<it->first<<' '<<"occurs "<<it->second<<endl;      }}void main(){CountWords(); cout<<endl;system("pause");}

0 0