本文主要是介绍一行文本中的最长单词,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题:已知 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;
}
这篇关于一行文本中的最长单词的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!