统计单词个数,并找出最长、最短的单词(9.39)

计算sentence中有多少个单词,并找出其中最长、最短的单词。

 

#include<iostream>
#include<vector>
#include<string>
using namespace std;

int main()
{
	
	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;

	//calculate the numbers of word
	string separators(" ,:.");//string对象separators用来表示分隔符集合

	string word;
	string::size_type beginPos=0,endPos=0;   //单词的起始、结束位置
	string::size_type counter=0;  //单词计数器
	string::size_type maxLen,minLen,wordLen;  //最长、最短的单词及下一单词的长度
	vector<string> longestWords,shortestWords;  //用来存储最长、最短单词的vector容器

	while((beginPos=sentence.find_first_not_of(separators,endPos))!=string::npos)
	{
		//找到下一单词的起始位置
		++counter;

		//找到下一单词的结束位置
		endPos=sentence.find_first_of(separators,beginPos);
		if(endPos==string::npos)
			wordLen=sentence.size()-beginPos;  //找不到分隔符,该单词即是最后一个单词
		else

		        wordLen=endPos-beginPos;
		//获取单词
		word.assign(sentence.begin()+beginPos,sentence.begin()+beginPos+wordLen);


		if(counter==1)
		{
			maxLen=minLen=wordLen;
			longestWords.push_back(word);
			shortestWords.push_back(word);
		}
		else
		{
			if(wordLen>maxLen)
			{
				//当前单词比最长单词更长
				maxLen=wordLen;
				longestWords.clear();  //清空当前容器
				longestWords.push_back(word);
			}
			else if(wordLen==maxLen)
				longestWords.push_back(word);

			if(wordLen<minLen)
			{
				//当前单词比最短单词还短
				minLen=wordLen;
				shortestWords.clear();
				shortestWords.push_back(word);
			}
			else if(wordLen==minLen)
				shortestWords.push_back(word);
		}
	}
	
	cout<<"sentence has words of "<<counter<<endl;
	cout<<"the longest word is: "<<endl;
	for(vector<string>::iterator it=longestWords.begin();it!=longestWords.end();++it)
		cout<<*it<<"\t";
	cout<<endl<<"and the length is: "<<maxLen<<endl;

	cout<<"the shortest word is: "<<endl;
	for(vector<string>::iterator it=shortestWords.begin();it!=shortestWords.end();++it)
		cout<<*it<<"\t";
	cout<<endl<<"and the length is: "<<minLen<<endl;


	return 0;
}

sentence has words of 17
the longest word is: 
perspicacious	
and the length is: 13
the shortest word is: 
we	of	10	us	
and the length is: 2

转载于:https://my.oschina.net/ppppower/blog/36499

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值