String类中一些常用的函数

find 与 rfind

# include <bits/stdc++.h>

using namespace std;

int main ()
{
    string a = "abcdefde",b = "de";
    int pos1 = a.find(b);//从左边开始查找
    cout<<pos1<<endl;//pos1 = 3
    int pos2 = a.rfind(b); //从右边开始查找
    cout<<pos2<<endl; //pos2 = 6
    return 0;
    /*如果没有查找到,则pos = -1*/
}

replace

string a.replace(int pos,int n,const char *str); //pos是从下标为POS的地方开始找,n为替换的长度,str为用来替换的字符串
# include <bits/stdc++.h>

using namespace std;

int main ()
{
    string a = "hello world",b = "C++";
    a.replace(6,5,b);
    cout<<a<<endl; //输出hello C++
}

insert 与 erase

insert(int pos,const char *str); //表示从下标为pos的前面插入str字符串
erase(int pos,int n) // pos 表示从下标为pos的地方开始,往后删除n个字符
# include <bits/stdc++.h>

using namespace std;

int main ()
{
    string a = "hello  ",b = "lll";
    a.insert(1,b);
    cout<<a<<endl; //输出hlllello
    a.erase(1,3);
    cout<<a<<endl; //输出hello
}

substr

substr(int pos,int n); //从下标为pos的地方截取n个长度的字符串
# include <bits/stdc++.h>

using namespace std;

int main ()
{
    string QQemail = "414750422@qq.com";
    int pos = QQemail.find("@");
    string SubStr = QQemail.substr(0,pos);
    cout<<SubStr<<endl; //输出414750422
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值