发现配套的习题答案有问题,稍作修改,得到正确的结果
int main()
{
string line1="We were her pride of 10 she named us:";
string line2="Benjamin, phoenux, the Prodigal";
string line3="and perspicacicous pacific Suzanne";
string sentence=line1+' '+line2+' '+line3;
string separators(" \t:,\v\r\n\f");//用作分隔符的字符
string word;
vector<string> maxv, minv;//存放最长及最短单词的vector容器
string::size_type max_len,min_len,len,count=0;//sentence中最长、最短单词以及下一单词的长度,单词数目
string::size_type start_pos=0,end_pos=0;//单词的起始及结束位置
start_pos=sentence.find_first_not_of(separators,end_pos);
while(start_pos!=string::npos){
count++;//统计单词的个数
end_pos=sentence.find_first_of(separators,start_pos);//找到下一处分隔符
if(end_pos==string::npos){//找到的是最后一个单词
len=sentence.size()-start_pos;
}
else {
len=end_pos-start_pos;
}
word.assign((sentence.begin()+start_pos),(sentence.begin()+start_pos+len));//用了string的assign函数:c.assign(b,e),b/e为迭代器
if(count==1){//以第一个单词为容器赋初值
max_len=min_len=len;
maxv.push_back(word);
minv.push_back(word);
}
else{
if(len>max_len){
max_len=len;
maxv.clear();
maxv.push_back(word);
}
else if(len==max_len){
maxv.push_back(word);
}
if(len<min_len){
min_len=len;
minv.clear();
minv.push_back(word);
}
else if(len==min_len){
minv.push_back(word);
}
}
start_pos=sentence.find_first_not_of(separators,end_pos);//找到下一处单词的开始
}
//输出单词数目
cout << "word amount:" << count << endl;
vector<string>::iterator iter;
//输出最长单词
cout << "longest word(s):" << endl;
iter = maxv.begin();
while(iter != maxv.end())
cout << *iter++ << endl;
//输出最短单词
cout << "shortest word(s):" << endl;
iter = minv.begin();
while(iter != minv.end())
cout << *iter++ << endl;
system("pause");
return 0;
}
运行结果: