问题01:如何把含定界符的字符串分割成多个字符串

使用basic_string中的find成员函数依次找到每个定界符,然后使用substr函数把每个子字符串复制出来。

#include<iostream>#include<string>usingnamespacestd;intmain(){strings="Name|Addr|Phone";charc='|';string::size_typei=0;string::size_typej=s.find(c,i);while(j!=string::npos){cout<<s.substr(i,j-i)<<endl;i=++j;j=s.find(c,i);}cout<<s.substr(i,s.length()-i)<<endl;
return0;}

问题02:如何使用一组定界符把一个字符串分解成多个片段

使用basic_string的find_first_of和find_first_not_of成员函数来列举字符串并交替地定位下一个特征符和非特征符。

#include<iostream>#include<string>usingnamespacestd;intmain(){strings="Name:Addr;Phone";stringd=":;";string::size_typei=s.find_first_not_of(d,0);string::size_typej=s.find_first_of(d,i);while(i!=string::npos&&j!=string::npos){cout<<s.substr(i,j-i)<<endl;i=s.find_first_not_of(d,j);j=s.find_first_of(d,i);}cout<<s.substr(i,s.length()-i)<<endl;return0;}

问题03:如何在字符串中查找字符

使用basic_string的find成员函数,几乎所有以单词"find"开始的函数。每一个函数都有一个basic_string::size_type参数pos,它用来让你能指明查找开始处的索引。函数返回值为basic_string::size_type,如果查找成功,返回值即为目标索引,如果查找失败,返回值为basic_string::npos。

find();rfind();find_first_of();find_first_not_of();find_last_of();find_last_not_of();

问题04:如何字符串中查找字符串

你可以使用定义在<algorithm>中的search算法。

问题05:如何比较两个字符串是否相同

你可以使用定义在<algorithm>中的equal算法。

问题06:如何统计文本文件中不同类型字符的数目

使用输入流读字符,一次一个,随着你读到的字符,增加相应的统计。判断函数可以使用<cctype>中定义的字符判断函数。

isalpha();isdigit();isupper();islower();isxdigit();isspace();iscntrl();ispunct();isalnum();isprint();isgraph();

#include<iostream>#include<map>#include<fstream>#include<cctype>#include<string>usingnamespacestd;intmain(){fstreamin("sample.txt",ios::in|ios::binary);map<string,unsignedint>cmap;charcur;while(in.get(cur)){
if(isalpha(cur))++cmap["alpha"];elseif(isdigit(cur))++cmap["digit"];elseif(ispunct(cur))++cmap["punct"];else++cmap["other"];}map<string,unsignedint>::iteratoriter=cmap.begin();for(;iter!=cmap.end();++iter)cout<<iter->first<<":"<<iter->second<<endl;return0;}

问题07:如何使你的文本右对齐或左对齐

使用流和标准流的格式标志右和左,他们都是定义在<ios>中ios_base的一部分。ios_base类模板中有很多标志可以用来格式化从流读进来的和写入流的数字和文本数据。控制文本对齐的是right和left。它们都是ios_base中的静态成员,都是fmtflags类型。可以使用ios_base::sef来设置格式标志。

out.setf(std::ios_base::right);

但是右对齐如果没有设置右边页面的空白宽度的话就没有意义。为了设置这个宽度,可以使用ios_base::width。

out.width(w);

当你用完你设置的格式标志时,你应该做的是清理掉它们。否则,这些标志将影响以后使用流的用户。

ios_base::fmtflagsflags= out.setf(ios_base::left);//setfreturnstheflagsthatwerealreadythereout.width(72);cout<<tmp<<endl;out.flags(flags);//resettooldflags