C++ Primer_顺序容器杂记(五)

2014-11-24 12:32:32 · 作者: · 浏览: 11
tr.find_first_of(numerics,pos))!=string::npos)
{
cout< pos++;
}
cout< //letter
pos=0;
while((pos=str.find_first_of(alpha,pos))!=string::npos)
{
cout< pos++;
}
cout< //find_first_not_of
//number
pos=0;
while((pos=str.find_first_not_of(numerics,pos))!=string::npos)
{
cout< pos++;
}
cout< //letter
pos=0;
while((pos=str.find_first_not_of(alpha,pos))!=string::npos)
{
cout< pos++;
}
cout< system("pause");
}

Exercise
9.39:
已知有如下 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 中有多少个单词,并指出其中
最长和最短的单词。如果有多个最长或最短的单词,则
将它们全部输出。

view plain
#include
#include
#include
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 separators(" \t\v\r\f,:");
cout< sentence+=" ";//添加结束标志
string::size_type word(0),slen(sentence.size()),llen(0),pos(0),end;
vectorlstr,sstr;//容器
//从头到尾遍历
for(end=sentence.find_first_of(separators,pos) ; pos!=string::npos ; pos=sentence.find_first_not_of(separators,end),end=sentence.find_first_of(separators,pos))
{
word++;
if(end-pos>llen)//发现更长的
{
llen=end-pos;
lstr.clear();//清空原容器
}
if(end-pos {
slen=end-pos;
sstr.clear();
}
if(end-pos==llen)//长度符合
{
lstr.push_back(string(sentence.begin()+pos,sentence.begin()+end));//进入容器
}
if(end-pos==slen)
{
sstr.push_back(string(sentence.begin()+pos,sentence.begin()+end));
}
}
cout<<"There are "< vector::iterator it=lstr.begin();
cout<<"There are "< while(it!=lstr.end())
cout<<*it++<<" ";
cout< it=sstr.begin();
cout<<"There are "< while(it!=sstr.end())
cout<<*it++<<" ";
cout< cin.get();
}

9.40用
string q1("when lilacs last in the dooryard bloom 'd'");
string q2("The child is the father of the man");
创建
string sentence("The child is in the dooryard");

view plain
#include
#include
using namespace std;

int main()
{
string q1("when lilacs last in the dooryard bloom 'd'");
string q2("The child is the father of the man");
string sentence;
sentence.assign(q2,q2.find("The child is "),string("The child is ").size());
// se