《primer-c++4》学习笔记-第exercise9.38
来源:互联网 发布:淘宝卖衣服代理 编辑:程序博客网 时间:2024/06/11 15:58
已知有如下 string 对象:
string line1 = "We were her pride of 10 she
named us:";
string line2 = "Benjamin, Phoenix, the
Prodigal"
string line3 = "and perspicacious pacific
Suzanne";
string sentence = line1 + ' ' + line2 + ' ' +
line3;
编写程序计算 sentence 中有多少个单词,并指出其中
最长和最短的单词。如果有多个最长或最短的单词,则
将它们全部输出
#include <iostream>
#include <string>#include <vector>
using namespace std;
int main()
{
string line1 = "We were her pride of 10 she named us:";
string line2 = "Benjamin, Phoenix, the Prodigal";
string line3 = "and perspicacious pacific Suzanne";
string sentence = line1 + ' ' + line2 + ' ' + line3;
string character("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
vector<string> Maxword,Minword;//记录最长和最短单词的vector容器
string::size_type count=0,wordlen,maxlen,minlen;//单词总数,当前单词的大小,最长单词的大小,最小单词的大小
string::size_type pos1=0;//单词的结束位置
string::size_type pos2=sentence.find_first_of(character);//单词的开始位置
pos1=sentence.find_first_not_of(character,pos1);
if(pos1==string::npos)
wordlen=sentence.size()-pos2;
else
wordlen=pos1-pos2;
string word;
word.assign(sentence,pos2,wordlen);//获取第一个单词
maxlen=minlen=wordlen;
Maxword.push_back(word);
Minword.push_back(word);
++count;
//依次处理后面的单词
while((pos2=sentence.find_first_not_of(character,pos1))!=string::npos)
{
++pos2;
pos1=sentence.find_first_not_of(character,pos2);
if(pos1==pos2)
;
else
{
++count;
if(pos1==string::npos)
wordlen=sentence.size()-pos2;
else
wordlen=pos1-pos2;
word.assign(sentence,pos2,wordlen);
if(wordlen>maxlen)
{
maxlen=wordlen;
Maxword.clear();
Maxword.push_back(word);
}
else if(wordlen==maxlen)
Maxword.push_back(word);
if(wordlen<minlen)
{
minlen=wordlen;
Minword.clear();
Minword.push_back(word);
}
else if(wordlen==minlen)
Minword.push_back(word);
}
}
//输出
cout<<"the count of words :"<<count<<endl;
vector<string>::iterator item;
cout<<"the longest words :"<<endl;
item=Maxword.begin();
while(item!=Maxword.end())
cout<<*item++<<endl;
cout<<"the shortest words :"<<endl;
item=Minword.begin();
while(item!=Minword.end())
cout<<*item++<<endl;
return 0;
}
0 0
- 《primer-c++4》学习笔记-第exercise9.38
- 【C++Primer学习笔记】第4章 数组和指针
- c++primer 4 学习笔记--第7章
- C++Primer第6章学习笔记
- C++primer学习笔记 第7章
- C++primer学习笔记第一天
- C++primer学习笔记《4》
- C++PRIMER学习笔记
- c++primer学习笔记
- c++primer学习笔记
- C++primer学习笔记
- c++primer 学习笔记
- C++Primer 学习笔记
- c++primer学习笔记
- C++Primer学习笔记
- C++PRIMER 学习笔记
- C++Primer学习笔记
- C++Primer学习笔记
- Mysql分区性能
- “编码”和“乱码”
- 【Unity开发】粒子效果穿透最上层UI的解决办法
- android 相同文件 在不同项目显示效果不一样
- C++中智能指针的设计和使用
- 《primer-c++4》学习笔记-第exercise9.38
- [ERROR] Event Scheduler: Failed to open table mysql.event
- MySQL锁解决并发问题详解
- App 研发录 阅读笔记 (6-9)(附代码)
- 状态压缩DP POJ 1321 棋盘问题
- Ubuntu14.04+Beanstalkd1.9+Golang最佳实践
- C++11 并发编程教程 - Part 3 : 锁的进阶与条件变量
- spring mvc常用注解@Component @Controller @Service @Repository
- SQL Server死锁总结