计算sentence中有多少个单词,并找出其中最长、最短的单词。
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
string line1("we were her pride of 10 she named us:");
string line2("Benjamin, phoenix, the Prodigal");
string line3("and perspicacious pacific Suzanne");
string sentence=line1+' '+line2+' '+line3;
//calculate the numbers of word
string separators(" ,:.");//string对象separators用来表示分隔符集合
string word;
string::size_type beginPos=0,endPos=0; //单词的起始、结束位置
string::size_type counter=0; //单词计数器
string::size_type maxLen,minLen,wordLen; //最长、最短的单词及下一单词的长度
vector<string> longestWords,shortestWords; //用来存储最长、最短单词的vector容器
while((beginPos=sentence.find_first_not_of(separators,endPos))!=string::npos)
{
//找到下一单词的起始位置
++counter;
//找到下一单词的结束位置
endPos=sentence.find_first_of(separators,beginPos);
if(endPos==string::npos)
wordLen=sentence.size()-beginPos; //找不到分隔符,该单词即是最后一个单词
else
wordLen=endPos-beginPos;
//获取单词
word.assign(sentence.begin()+beginPos,sentence.begin()+beginPos+wordLen);
if(counter==1)
{
maxLen=minLen=wordLen;
longestWords.push_back(word);
shortestWords.push_back(word);
}
else
{
if(wordLen>maxLen)
{
//当前单词比最长单词更长
maxLen=wordLen;
longestWords.clear(); //清空当前容器
longestWords.push_back(word);
}
else if(wordLen==maxLen)
longestWords.push_back(word);
if(wordLen<minLen)
{
//当前单词比最短单词还短
minLen=wordLen;
shortestWords.clear();
shortestWords.push_back(word);
}
else if(wordLen==minLen)
shortestWords.push_back(word);
}
}
cout<<"sentence has words of "<<counter<<endl;
cout<<"the longest word is: "<<endl;
for(vector<string>::iterator it=longestWords.begin();it!=longestWords.end();++it)
cout<<*it<<"\t";
cout<<endl<<"and the length is: "<<maxLen<<endl;
cout<<"the shortest word is: "<<endl;
for(vector<string>::iterator it=shortestWords.begin();it!=shortestWords.end();++it)
cout<<*it<<"\t";
cout<<endl<<"and the length is: "<<minLen<<endl;
return 0;
}
sentence has words of 17
the longest word is:
perspicacious
and the length is: 13
the shortest word is:
we of 10 us
and the length is: 2