习题9.39 计算string 中最短和最长的单词

#include<iostream>
#include<string>
#include<vector>
using namespace std;
//计算有多少个单词,并输出最短和最长的单词
int main(int argc,char **argv)
{
	string sentence = "We were her pride of:Benjamin, Phoenix, the Prodigal and perspicacious pacific Suzanne";
	string words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
	vector<string> vecstr;
	string::size_type pos = 0;
	string::size_type end = 0;
	int max = 0;
	int min = sentence.length();
	string temp;

	while(pos!=string::npos&&end!=string::npos)
	{				
		pos = sentence.find_first_of(words,pos);
		end = sentence.find_first_not_of(words,pos);

		temp = sentence.substr(pos,end-pos);
		vecstr.push_back(temp);
			
		if(temp.length()>max)
			max = temp.length();
		if(temp.length()<min)
			min = temp.length();

		pos = end+1;
	}
	
	cout<<"the max word is:";
	for(vector<string>::iterator it=vecstr.begin();it!=vecstr.end();++it)
	{
		if((*it).length()==max)
			cout<<*it<<" ";
	}

	cout<<"\nthe min word is:";
	for(vector<string>::iterator it=vecstr.begin();it!=vecstr.end();++it)
	{
		if((*it).length()==min)
			cout<<*it<<" ";
	}
	cout<<endl;

}

  

版权声明:本文为chhyong88原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/chhyong88/p/2275409.html