// 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;
}
统计单词个数和查找最长最短单词
最新推荐文章于 2024-03-08 08:51:52 发布