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()操作,将单词压入容器
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 << " "; }
相关文章推荐
- 编写程序计算sentence中有多少个单词,并指出其中最长和最短的单词 C++
- 计算字符串中有多少单词,并输出最长最短的单词。(c++primer 9.39)
- 计算共有多少个单词,并输出最长和最短的单词
- 习题9.39输出最长和最短单词
- 习题9.39 计算string 中最短和最长的单词
- 习题 7.10 写一个函数,输入一行字符,将此字符串中最长的单词输出。
- 这次带来的小程序是:确定一个字符串有多少个单词,然后最长单词和最短单词有哪些
- C++ Primer 课后习题9.39 统计单词个数并记录最大单词和最短单词
- 03_统计单词个数、求阶乘、输出最短和最长的字符串
- 输出句子中的最长单词和最短单词
- 输入一串字符,找出最长和最短单词并输出
- 最长最短单词
- 给定任意字符串,计算一共能组合成多少个单词bing
- 一个字符串去除里面的数字,把剩下的字符输出 和 一个字符串计算最大单词的长度并输出这个单词
- 最长最短单词
- 每天一道LeetCode-----计算从二维数组的左上角到达右下角的所有路径数及最短的那条,如果存在障碍物时又是多少
- c++ primer 习题之 单词转换程序
- 用一个函数实现将一行字符串中最短的单词输出。此行字符串从主函数传递给该函数。假设字符串中包含的单词以空格作为分隔符号,例如”Asia Games 2010 is held in GuangZhou.”,其中最短的单词是”is”和”in”。
- 动态规划算法计算网络的最长路线和最短路线
- 计算一个字符串中有多少个单词