代码如下:
# include<iostream>
# include<stdio.h>
#include<string>
#include <vector>
#include <iomanip>
using namespace std;
int main()
{
int pos;
string word;//缓存字符串
string sep(" ,.?!:\"\t\n();");
vector<string> word_set;//确认不是stopword词汇后的单词集放进去
vector<int> word_num;//单词集对应的次数
vector<string> stop_word;//应删去的词
typedef vector<string>::size_type vect_sz;
vect_sz size = 0;//向量的size
bool flag1,flag2;
stop_word.push_back("to");
stop_word.push_back("in");
stop_word.push_back("will");
stop_word.push_back("of");
stop_word.push_back("be");
stop_word.push_back("and");
stop_word.push_back("a");
stop_word.push_back("the");
cout<<"enter the text"<<endl;
while(cin>>word)
{
// 除去每一个word多余的符号
pos = word.find_first_of(sep);
if ( pos == word.size()-1) //符号出现在尾部
{
string tmp(word.substr(0, pos));
word = tmp;
}
else if (pos == 0)//符号出现在头部
{
string::size_type pos2 = word.find_first_not_of(sep, 1);
pos = word.find_first_of(sep, pos2+1);
string tmp(word.substr(pos2, pos-1));
word = tmp;
}
// 除去stop word
flag1=false;
for (int i = 0; i < stop_word.size(); i++)
{
if (word==stop_word[i])
{
flag1=true;
}
}
if (flag1)
{
continue;
}
//判断单词集是否存在单词或者与word相同的单词
size = word_set.size();
flag2 = true;
for (int i=0; i!=size; ++i)
if (word_set[i] == word) {
++word_num[i];
flag2 = false;
break;
}
//存入单词集并在次数向量中对应+1
if (flag2)
{
word_set.push_back(word);
word_num.push_back(1);
}
}
//给单词次数进行降序处理,同时改变单词顺序
for (int i = 0; i < word_set.size()-1; i++)
{
int currentmax = word_num[i];
int currentmaxindex = i;
string temps_storage;
for (int j=i+1; j < word_set.size(); j++)
{
if (word_num[j]>currentmax)
{
currentmax = word_num[j];
temps_storage = word_set[i];
currentmaxindex = j;
}
}
if (currentmaxindex!=i)
{
word_num[currentmaxindex] = word_num[i];
word_num[i]=currentmax;
word_set[currentmaxindex] = word_set[i];
word_set[i] = temps_storage;
}
}
// 输出单词以及对应的频率
for (int i = 0; i < word_num.size(); i++)
{
cout<<word_set[i]<<" "<<word_num[i]<<endl;
}
return 0;
}
输入如下:There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream; go where you want to go; be what you want to be, because you have only one life and one chance to do all the things you want to do.
如果把排序部分的代码删除,得到的是正确的统计频率:
There 1
are 1
moments 1
life 2
when 1
you 7
miss 1
someone 1
so 1
much 1
that 1
just 1
want 5
pick 1
them 2
from 1
your 1
dreams 1
hug 1
for 1
real 1
Dream 1
what 2
dream 1
go 2
where 1
because 1
have 1
only 1
one 2
chance 1
do 2
all 1
things 1
保留排序部分代码会出现如下错误输出:
There 7
are 5
moments 2
moments 2
when 2
There 2
miss 2
someone 2
so 1
much 1
that 1
just 1
are 1
pick 1
moments 1
from 1
your 1
dreams 1
hug 1
for 1
real 1
Dream 1
when 1
dream 1
There 1
where 1
because 1
have 1
only 1
miss 1
chance 1
someone 1
all 1
things 1
为什么会出现这种情况