好久么弄C++了,好像也没在项目中正式的用过C++了,这里复习下。先复习下string。
CONTENTS
API:
http://www.cplusplus.com/reference/string/string/
上面这个网址内容非常好,每个函数都有实例。
学习代码:
#include <iostream> #include<string> //http://www.cplusplus.com/reference/string/string/ std::cout<<"Hello World\n"; std::string s1 = "hello"; std::string s2("world"); std::string s3 = s1 + " " + s2; std::cout<<s1<<std::endl; std::cout<<s2<<std::endl; std::cout<<s3<<std::endl; std::string s4 = "hello world"; std::cout<<(s3 == s4 ? "same":"different")<<std::endl; std::cout<<"s4[2]:"<<s4[2]<<std::endl; s4[2] = 'x'; std::cout<<"s4[2]:"<<s4[2]<<std::endl; std::cout<<(s4.empty()? "YES":"NO")<<std::endl; std::cout<<"s4.length():"<<s4.length()<<std::endl; s4.clear(); std::cout<<(s4.empty()? "YES":"NO")<<std::endl; std::cout<<"s4.length():"<<s4.length()<<std::endl; s4 = "hello world"; std::string::size_type pos = s4.find("l"); if (std::string::npos == pos) { std::cout<<"not find \n"; }else { std::cout<<"pos:"<<pos<<std::endl; } pos = s4.rfind("l"); if (std::string::npos == pos) { std::cout<<"not find \n"; }else { std::cout<<"pos:"<<pos<<std::endl; } pos = s4.find_first_of("l"); if (std::string::npos == pos) { std::cout<<"not find \n"; }else { std::cout<<"pos:"<<pos<<std::endl; } std::cout<<s4<<std::endl; s4.insert(0,"~~NEW~~"); std::cout<<s4<<std::endl; s4.erase(0,5); std::cout<<s4<<std::endl; s4.replace(0,5,"12345"); std::cout<<s4<<std::endl; s4.append("This is tail"); std::cout<<s4<<std::endl; s4 = s4.substr(2,3); std::cout<<s4<<std::endl; //Searches the string for the first character that matches 【any】 of the characters specified in its arguments. std::string str ("Please, replace the vowels in this sentence by asterisks."); std::size_t found = str.find_first_of("aeiou"); while (found!=std::string::npos) { str[found]='*'; found=str.find_first_of("aeiou",found+1); } std::cout << str << '\n';
输出:
Hello World hello world hello world same s4[2]:l s4[2]:x NO s4.length():11 YES s4.length():0 pos:2 pos:9 pos:2 hello world ~~NEW~~hello world ~~hello world 12345lo world 12345lo worldThis is tail 345 Pl**s*, r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.
发表评论