如果您无法下载资料,请参考说明:
1、部分资料下载需要金币,请确保您的账户上有足够的金币
2、已购买过的文档,再次下载不重复扣费
3、资料包下载后请先用软件解压,在使用对应软件打开
toupper,tolower地球人都知道C++的string没有toupper,好在这不是个大问题,因为我们有STL算法:strings("heLLo");transform(s.begin(),s.end(),s.begin(),toupper);cout<<s<<endl;transform(s.begin(),s.end(),s.begin(),tolower);cout<<s<<endl;当然,我知道很多人希望的是s.to_upper(),但是对于一个这么通用的basic_string来说,的确没办法把这些专有的方法放进来。如果你用booststringalgo,那当然不在话下,你也就不需要读这篇文章了。------------------------------------------------------------------------trim我们还知道string没有trim,不过自力更生也不困难,比toupper来的还要简单:strings("hello");s.erase(0,s.find_first_not_of("/n"));cout<<s<<endl;s.erase(s.find_last_not_of('')+1);cout<<s<<endl;注意由于find_first_not_of和find_last_not_of都可以接受字符串,这个时候它们寻找该字符串中所有字符的absence,所以你可以一次trim掉多种字符。-----------------------------------------------------------------------erasestring本身的erase还是不错的,但是只能erase连续字符,如果要拿掉一个字符串里面所有的某个字符呢?用STL的erase+remove_if就可以了,注意光remove_if是不行的。strings("hello,world.saybye");s.erase(remove_if(s.begin(),s.end(),bind2nd(equal_to<char>(),'')),s.end());上面的这段会拿掉所有的空格,于是得到hello,world.saybye。-----------------------------------------------------------------------replacestring本身提供了replace,不过并不是面向字符串的,譬如我们最常用的把一个substr换成另一个substr的操作,就要做一点小组合:strings("hello,world");stringsub("ello,");s.replace(s.find(sub),sub.size(),"appy");cout<<s<<endl;输出为happyworld。注意原来的那个substr和替换的substr并不一定要一样长。-----------------------------------------------------------------------startwith,endwith这两个可真常用,不过如果你仔细看看string的接口,就会发现其实没必要专门提供这两个方法,已经有的接口可以干得很好:strings("hello,world");stringhead("hello");stringtail("ld");boolstartwith=s.compare(0,head.size(),head)==0;cout<<boolalpha<<startwith<<endl;boolendwith=s.compare(s.size()-tail.size(),tail.size(),tail)==0;cout<<boolalpha<<endwith<<endl;当然了,没有s.startwith("hello")这样方便。------------------------------------------------------------------------toint,todouble,tobool...这也是老生常谈了,无论是C的方法还是C++的方法都可以,各有特色:strings("123");inti=atoi(s.c_str());cout<<i<<endl;intii;stringstream(s)>>ii;cout<<ii<<endl;stringsd("12.3");doubled=atof(sd.c_str());cout<<d<<endl;doubledd;stringstream(sd)>>dd;cout<<dd<<endl;stringsb("true");bool