《c++ Primer(第四版)》习题 9.39

#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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值