要求:用户输入一段话,输出每个单词出现的次数
如输入:hello my friend . I miss you , my friend
输出:单词 次数
hello 1
my 2
friend 2
I 1
miss 1
you 1
#include
#include
#include
using namespace std;
int main()
{
string sen;//用来记录用户输入的句子
string word[100];
int a,b;
int times;//用来计相同单词的数目
string::size_type first=0,end=0;
int counter=1;
cout<<"请输入一段话:";
getline(cin,sen);
int i=0;//word数组的下标
//将所有标点符号转化为空格
for(int j = 0;j<sen.size();j++)
{
if(' ' == sen[j] || ',' == sen[j] || '.' == sen[j] || '!' == sen[j] || ';' == sen[j] || '?' == sen[j])
sen[j] = ' ';
}
//用空格作为分隔符将字符串中的单词分隔出来
while(1)
{
if(((end=sen.find(' ',first)) != string::npos)||((end=sen.find(' ',first)) != string::npos)||((end=sen.find(' ',first)) != string::npos))
{
word[i++]=sen.substr(first,end-first);
first=end+1;
counter++;
}
else
break;
}
word[i]=sen.substr(first,sen.size()-first);
cout<<"word"<<setw(13)<<"times"<<endl;
cout<<endl;
//对比字符串函数中单词出现的次数
for(a=0;a<counter-1;a++)
{
times=0;
for(b=0;b<counter;b++)
{
if(word[a] == word[b])
times++;
}
}
for(int k=0;k<counter;k++)
{
cout<<word[k]<<setw(13)<<times<<endl;
}
return 0;
}
我的结果这么是这样啊?
哪错了啊?我实在搞不懂了。。大家帮我看一看。。