#include <string>
#include <vector>
#include <iostream>
using namespace std;
void out_put_vector(vector<string>& arg)
{
vector<string>::iterator iter = arg.begin();
while(iter != arg.end())
{
cout<<*iter<<endl;
iter++;
}
return;
}
void fresh_long_and_short(string::size_type& longest, string::size_type& shortest,string word,
vector<string>& longestWord, vector<string>& shortestWord)
{
string::size_type wordLen = word.size();
if(wordLen > longest)
{
longest = wordLen;
longestWord.clear();
longestWord.push_back(word);
}
else if(wordLen == longest)
{
longestWord.push_back(word);
}
if(wordLen < shortest)
{
shortest = wordLen;
shortestWord.clear();
shortestWord.push_back(word);
}
else if(wordLen == shortest)
{
shortestWord.push_back(word);
}
}
void fun_939()
{
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;
string punc(" ,:");
string::size_type wordBegin = 0;
string::size_type wordLen = 0;
string::size_type wordEnd = 0;
string::size_type i = 0;
int wordNum = 0;
string::size_type longest = 0;
string::size_type shortest = 100;
vector<string> longestWord;
vector<string> shortestWord;
while((i = sentence.find_first_not_of(punc, i))!=string::npos)
{
wordBegin = i;
wordEnd = (i = sentence.find_first_of(punc, i)) != string::npos?(i-1):(sentence.size()-1);
wordLen = wordEnd - wordBegin + 1;
fresh_long_and_short(longest, shortest, sentence.substr(wordBegin, wordLen), longestWord, shortestWord);
wordNum++;
}
cout<<"Words Num: "<<wordNum<<endl;
cout<<"Longest Word Len: "<<longest<<endl;
out_put_vector(longestWord);
cout<<"shortest Word Len: "<<shortest<<endl;
out_put_vector(shortestWord);
}
《c++ Primer(第四版)》习题 9.39
最新推荐文章于 2024-06-04 00:29:08 发布