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

来源:互联网 发布:琉璃神社的备用域名 编辑:程序博客网 时间:2024/06/01 10:28
// 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
原创粉丝点击