c++string容器字符串查找替换、比较、提取、插入和删除以及string和c风格的字符串的转换

c++string容器字符串查找替换

//c++string容器字符串查找替换
#include<string>
#include<iostream>
#include<cstring>
using namespace std;

int main(){
    //int find(const string &str,int pos=0)const;
    //查找第一次出现的位置,从pos开始查找
    string str1 = "ehhe:haha:xixi:haha:heihei";
    string tmp = "haha";
    cout<<str1.find(tmp)<<endl;
    cout<<str1.find(tmp,10)<<endl;

    cout<<str1.find("haha")<<endl;

    //string& replace(int pos,int n,const string& str);
    //替换str第一次出现的位置,从pos开始查找
    str1.replace(5,4,"###");
    cout<<str1<<endl;

    string str2="www.17171272.sex.person.77.com";
    while(1){
        int ret = str2.find("sex");
        if(ret>str2.size()){
            cout<<"遍历查找完成"<<endl;
            break;
        }
        str2.replace(ret,strlen("sex"),"***");
    }
    cout<<str2<<endl;
    return 0;
}
5
15
5
ehhe:###:xixi:haha:heihei
遍历查找完成
www.17171272.***.person.77.com

c++string容器字符串的比较

//c++string容器字符串的比较
#include<iostream>
#include<string>
using namespace std;
int main(){
    //compare函数在>时返回1, <是返回-1,等于时返回0
    string str1 = "hehe";
    string str2 = "haha";
    cout<<str1.compare(str1)<<endl;//1
    cout<<str1.compare("lala")<<endl;//-1
    cout<<str1.compare("hehe")<<endl;//0
    return 0;
}

c++string容器字符串的提取

//c++string容器字符串的提取
#include<iostream>
#include<string>
using namespace std;
int main(){
    //string substr(int pos=0,int n=n)const;
    //返回由pos开始的n个字符组成的字符串
    string str1="hehehe:ha:xixixi:lalala:heihei";
    cout<<str1.substr(5,4)<<endl;

    int pos = 0;
    while(1){
        int ret = str1.find(":",pos);//从pos开始寻找":"
        if(ret<0){
            break;
        }
        string tmp =str1.substr(pos,ret-pos);
        cout<<tmp<<endl;
        pos=ret+1;
    }
    return 0;
}
e:ha
hehehe
ha
xixixi
lalala

c++string容器字符串的插入和删除

//c++string容器字符串的插入和删除
#include<iostream>
#include<string>
using namespace std;
int main(){
    string str1="hello world";
    str1.insert(5,"hehe");
    cout<<str1<<endl;

    str1.erase(5,4);//删除hehe
    cout<<str1<<endl;

    //清空字符串
    str1.erase();
    cout<<str1.size()<<endl;   
    return 0;
}
hellohehe world
hello world
0

string和c风格的字符串的转换

//c++string容器字符串的插入和删除
#include<iostream>
#include<string>
using namespace std;
int main(){
    string str1;
    const char* str2 = "hello str2";

    //char*转string可以直接完成
    str1 = str2;
    cout<<str1<<endl;

    //string不能直接转换成char* ,必须借助string类中的c_str()
    string str3="hello str3";
    string str4 = const_cast<char*>(str3.c_str());
    cout<<str4<<endl;

    return 0;
}
hello str2
hello str3
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

踏过山河,踏过海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值