统计单词个数和查找最长最短单词

// 9_39.cpp : 定义控制台应用程序的入口点。
//统计单词个数,且输出最长的单词,如有多个输出多个


#include "stdafx.h"
#include<string>
#include<iostream>
#include<vector>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	string sentence ("we were her pride of 10 she named us: bejamin,phonex");
	string separators(" \n\t,:\r\f");

	//声明变量
	string word;
	vector<string> longestWords,shortestWords;
	string::size_type startPos = 0,endPos = 0;
	string::size_type maxLen=0,minLen =0,wordLen=0,count =0;

	//每次循环处理其中的一个单词
	while((startPos= sentence.find_first_not_of(separators,endPos))!= string::npos)
		{
			//单词起始位置
			count++;
			endPos =sentence.find_first_of(separators,startPos);//单词结束位置

			//查找单词长度
			if(endPos == string::npos)//如果是最后一个单词
				wordLen = sentence.size()-startPos;
			else
			{
				wordLen= endPos - startPos;
			}
			//获取单词
			word.assign(sentence.begin()+startPos,sentence.begin()+startPos+wordLen);

			//设置下次查找的位置
			startPos = sentence.find_first_not_of(separators,endPos);

			if(count == 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(minLen > wordLen)
				{
					minLen = wordLen;
					shortestWords.clear();
					shortestWords.push_back(word);
				}
				else if(minLen ==  wordLen)
					shortestWords.push_back(word);
			}
	}

		//输出单词数目
			cout << "words amount:" << count <<endl;
		//输出最长单词
			vector<string>::iterator iter = longestWords.begin();
			while(iter!=longestWords.end())
				cout << *iter++<< endl;//++优先级高于*

			vector<string>::iterator iter1 = shortestWords.begin();
			while(iter1 != shortestWords.end())
				cout << *iter1++<< endl;//++优先级高于*


			system("pause");
			return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值