C++STL string类中的函数及注意事项一

  1. 字符串类的创建:
#include<iostream>
#include<string>
using namespace std;
int main(){
    //创建string。
    string s1;
    string s2("How are you?");
    string s3(s2);
    string s4(s2,0,3);//注意0是起始位置,3是偏移量。 
    string s5="How are you?"; 
    string s6=s2+"Fine";
    string s7(s5.begin(),s5.end());
    string s8(s5.begin()+4,s5.begin()+7);
    cout<<"创建string类的所有结果:"<<endl;
    cout<<s2<<endl<<s3<<endl<<s4<<endl<<s5<<endl<<s6<<endl<<s7<<endl<<s8<<endl;
}

2,字符串类的子串操作

#include<iostream>
#include<string>
using namespace std;
int main(){
    //字符串子串操作 
    /*插入*/
    cout<<"插入操作"<<endl;
    string s=" do";
    cout<<"最初的长度:"<<s.size()<<endl;
    s.insert(0,"How");//从0位置插入“HOW”
    s.append(" you");//在原串的最后加上参数。 
    s=s+" do?";
    cout<<"最后的长度"<<s.size()<<endl;
    cout<<s<<endl; 
    /*替换*/
    cout<<"替换操作:"<<endl; 
    string ss="what's your name?";
    ss.replace(7,4,"her");//7代表替换的位置,4代表要从原字符串删除的个数。
    cout<<ss<<endl;
} 

猜你喜欢

转载自blog.csdn.net/light2chasers/article/details/80644056
今日推荐