问题:已知 string sentence="We were her pride of 10 she named us: Benjamin, Phoenix, the Pordigal and perspicacious pacific Suzanne.";
要求:计算sentence中有多少个单次,并指出其中最长和最短的单词,如果有多个,则将它们全部输出。
解法:使用find_first_of 和find_first_not_of,寻找到单词的起始位置,以剔除标点;
使用vector存放最长和最短单词:通过贪心算法,寻找“最**”单词
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){
string sentence="We were her pride of 10 she named us: Benjamin, Phoenix, the Pordigal and perspicacious abcdefghijklmnopqrstuvwxyz pacific Suzanne.";
string separators="\t\f\r\n\v:,. ";//作为分隔符
string::size_type maxLen,minLen,wordLen,count=0;
string word;
vector<string> longestWords, shortestWords;
string::size_type startPos=0,endPos=0;
while( (startPos=sentence.find_first_not_of(separators,endPos) ) !=string::npos){//npos是一个常数,用来表示不存在的位置
++count;
//找到下一个单词的结束位置
endPos=sentence.find_first_of(separators,startPos);
//若找不到下一个分隔符,则说明该单词为最后一个单词
if(endPos==string::npos){
wordLen=sentence.size()-startPos;
}
else{
wordLen=endPos-startPos;
}
//注意这里不要是sentence.begin()+endPos;有可能endPos为string::npos;
//word.assign(sentence.begin()+startPos, sentence.begin()+startPos+wordLen);
word=sentence.substr(startPos, wordLen);//从startPos开始,wordLen个字母构成的子串
/
if(count==1){
longestWords.push_back(word);
shortestWords.push_back(word);
maxLen=minLen=wordLen;
}else{
if(wordLen>maxLen){
longestWords.clear();
longestWords.push_back(word);
maxLen=wordLen;
}else if(wordLen==maxLen){
longestWords.push_back(word);
}
if(wordLen<minLen){
shortestWords.clear();
shortestWords.push_back(word);
minLen=wordLen;
}else if(wordLen==minLen){
shortestWords.push_back(word);
}
}// end of else
}//end of while
//输出单词数目
cout<< "word amount: "<< count <<endl;
vector<string>::iterator iter;
//输出最长单词
cout<< "longest words: "<<endl;
iter=longestWords.begin();
while( iter!=longestWords.end() )
cout<< *iter++ <<endl;
//输出最短单词
cout<< "shortest words: "<<endl;
iter=shortestWords.begin();
while(iter!=shortestWords.end())
cout<< *iter++ <<endl;
return 0;
}