您的位置:首页 > 编程语言 > C语言/C++

C++ Primer 9.40习题 计算sentence有多少个单词,并输出最长、最短的单词d

2012-12-09 22:42 501 查看
代码思路:

1、单词数 = 空格数 + 1

2、采用迭代器遍历sentence,用两个迭代器b,e来锁定一个单词,并用一个string对象tmp记录该单词

3、由于最长、最短的单词可能不止一个,所以用vector<string>存储最长、最短单词,当发现一个最长的单词时,先调用clear清空该容器,然后再用assign把单词存入maxlegth,遇到长度相同的时采用push_back()操作,将单词压入容器

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string line1 = "we are her pride of 10 she named us";
string line2 ="benjamin phoenix 12 the 13 prodegal";
string line3 ="and perspicacious pacific suzanne";

string sentence = line1 + ' ' + line2 + ' ' + line3;
string::iterator iter = sentence.begin();
string::iterator b, e;			//记录一个单词的范围
string tmp;					//当前单词
int min = 100;				//最短单词
int max = 0;				//最长单词

vector<string> maxlength;	//存储最长单词
vector<string> minlength;		//存储最短单词
int wordcount = 0;			//单词计数

while(*iter == ' ')			//忽略前面的空格
++iter;

for(b = iter; iter != sentence.end();  ++iter)
{
//if(*iter != ' ')

if(*iter == ' ')
{
e = iter;	//单词终点
tmp.assign(b, e);		//当前单词

if((int)tmp.size() > max)
{
maxlength.clear();
max = tmp.size();
maxlength.push_back(tmp);
}
else if((int)tmp.size() == max)
maxlength.push_back(tmp);

if((int)tmp.size() < min)
{
minlength.clear();
min = tmp.size();
minlength.push_back(tmp);
}
else if((int)tmp.size() == min)
minlength.push_back(tmp);

b = iter + 1;          //新单词的起点
++wordcount;		//单词数加1
}
}
cout << "the sum of the letter is: " << wordcount + 1 << endl;
cout << "the longest length is: " << max << "  there are: " << endl;
for(vector<string>::iterator i = maxlength.begin(); i != maxlength.end(); ++i)
cout << *i << "  ";
cout << endl;
cout << "the shortest length is: " << min << "  there are: " << endl;
for(vector<string>::iterator i = minlength.begin(); i != minlength.end(); ++i)
cout << *i << "  ";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐