STL之string容器极其相关操作

C++标准库中的string容器是一个非常实用的字符序列,它可以用于存储和操作字符串。

1:string的构造函数

void test01(){

    string s1;//默认构造

    const char*str="hello world";
    string s2(str);

    string s3(s2);

    string s4(11,'b');//创建11个b
    cout<<s2<<endl;
    cout<<s3<<endl;
    cout<<s4;
}//string构造函数

2:string赋值

void test02(){
    string str1;
    str1="hello world";
    cout<<str1<<endl;

    string str2;
    str2=str1;
    cout<<str2<<endl;

    string str3;
    str3='a';
    cout<<str3<<endl;

    string str4;
    str4.assign("hello C++");
    cout<<str4<<endl;

    string str5;
    str5.assign("hello C++",5);
    cout<<str5<<endl;

    string str6;
    str6.assign(str5);
    cout<<str6<<endl;

    string str7;
    str7.assign(7,'v');
    cout<<str7<<endl;
}//string赋值

3:字符串拼接

void test03(){
    string s1="my";
    s1+="apple";
    cout<<s1<<endl;

    string s2="my";
    s2+='s';
    cout<<s2<<endl;

    string s3="my";
    s3+=s1;
    cout<<s3<<endl;

    string s4="I";
    s4.append("love");
    cout<<s4<<endl;
    s4.append("game1234",4);
    cout<<s4<<endl;
    // s4.append(s3);
    // cout<<s4<<endl;
    s4.append(s3,0,2);//只截取s3从0开始2个字符
    cout<<s4<<endl;
}//字符串拼接

4:字符串查找

void test04(){
    string s1="abcdefgde";
    int pos=s1.find("de");
    if(pos==-1){
        cout<<"no"<<endl;
    }
    else{
        cout<<pos<<endl;//返回d第一次出新的位置
    }
    int ppos=s1.rfind("de");
    cout<<ppos<<endl;//rfind是从右往左查找,find是从左往右查找

}//字符串的查找

5:字符串的替换

void test05(){
    string str1="abcdefg";
    str1.replace(1,3,"1111");//从1个位置起3个字符被替换为"1111"
    cout<<str1<<endl;

}//字符串的替换

6:字符串的比较

void test06(){
    string s1="my";
    string s2="my";
    if(s1.compare(s2)==0){
        cout<<"yes";
    }//比较两个字符串
}//字符串的比较

7:字符串的存取和修改

void test07(){
    string str="hello";
    //存取
    for(int i=0;i<str.size();i++){
        //cout<<str[i];//通过[]访问
        cout<<str.at(i)<<" ";//通过at访问;
    }
    //修改
    str[2]='p';
    str.at(1)='x';
    cout<<str<<endl;
}//字符存取和修改

8:字符串插入和修改

void test08(){
    string str="hello";
    //插入
    str.insert(1,"my");//在第一个位置插入my
    cout<<str<<endl;

    //删除
    str.erase(1,3);
    cout<<str<<endl;//在第一个位置删除3个字符

}//string插入删除

9:string求子串

void test09(){
    string str="hello";
    string sub=str.substr(1,3);//从第一个位置截取3个字符
    cout<<sub<<endl;

    string email="gaogao@qq.com";
    int pos=email.find('@');//6
    string sub1=email.substr(0,pos);//6
    cout<<sub1<<endl;
}//string 求子串

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值