标准库string常用方法

string常用方法定义及初始化

string类型提供 与vector相同的操作,可视为字符容器,与vetor容器不同的是,string容器不支持以栈方式操作容器,在string类型中不能使用front、back和pop_back操作

string s1;string s2=”hello”;cout<<s2<<endl;size() 和empty操作string s1;string s2=”hello”;cout<<s2.size()<<endl;if(s1.empty()){cout<<“”<<endl;}[]操作符 string s2=”hello”;for (int i=0; i<s2.size(); i++) {cout<<s2[i]<<” “<<endl;}关系操作符

如果两个string对象的字符不同,则比较第一个不匹配的字符 如果两个string对象的长度不同,且短的string对象与长的string对象的前面部分相同,则短的string对象小于长的string对象

string s1 = “hello world”;string s2 = “hello”;string s3 = “hiya”;string s4=”hello world”;if(s1 >s2){cout <<“s1小于s2″<<endl;}if(s1<s3) {cout<<“s1小于s3″<<endl;}if(s1 == s4) {cout<<“s1等于s4″<<endl;}两个string对象相加

string对象可以通过加法被定义为链接,使用+或+=连接起来

string s1 = “hello world “;string s2 = “hello”;string s3 =s1 + s2;cout<<s3<<endl;支持迭代器 string s1 = “hello world “;string s2 = “hello”;string s3 =s1 + s2;string::iterator iter=s3.begin();while(iter != s3.end()) {cout<<*iter++<<endl;}insert、erase操作string s3 = “hello world “;string::iterator iter=s3.begin();s3.insert(s3.begin(),3,’c’);while(iter!=s3.end()){cout<<*iter++<<endl;}s3.erase(s3.begin(),s3.begin()+5);iter=s3.begin();while(iter!=s3.end()){cout<<*iter++<<endl;}

只适用于string类型的操作

substr操作string s3 = “hello world “;cout<<s3.substr(1,3)<<endl;append函数

用于修改string对象

string s3 = “hello world “;s3.append(“facebook”);cout<<s3<<endl;replace函数

I.s.replace(pos,len,args). 删除s中从下标pos开始开始的len个字符

string s3 = “hello world “; cout<<s3.replace(0,2,”ccc”)<<endl;

II. s.replace(b,e,args),删除迭代器b和e范围内所有的字符,,用args替换

string s3 = “hello world “;s3.replace(s3.begin(),s3.begin()+3,”facebook”);cout<<s3<<endl;find操作string s3 = “hello world “;string::size_type pos1=s3.find(“llo”);cout<<pos1<<endl;

一个人目睹沿途的风景,拿着相机,拍下沿途上的风景,

标准库string常用方法

相关文章:

你感兴趣的文章:

标签云: