C++string中replace()替换函数

C++string中replace()函数

  • basic_string& replace(size_type pos, size_type n, const basic_string& str)
    -用str替换原串中下标为pos开始数的n个字符。

  • basic_string& replace(iterator first, itrator last, const basic_string& str)
    和上面类似。

  • basic_string& replace(size_type pos, size_type n, size_type m, char c)
    用m个字符c替换原串中下标为pos开始数的n个字符。

  • basic_string& replace(iterator first, itrator last, size_type m, char c)
    和上面类似。

  • basic_string& replace(size_type pos1, size_type n, const basic_string& str, size_type pos2, size_type m)
    用str从pos2开始数的m个字符替换原串从pos1开始数的n个字符。

代码:

#include<iostream>
using namespace std;
int main()
{
    string str="She study really hard!";
    str=str.replace(0,3,"He");//原串从下标为0数的3个字符She用He替换
    cout<<str<<endl;

    string str1="She study really hard!";
    str1=str1.replace(str1.begin(),str1.begin()+3,"He");
    cout<<str1<<endl;//原串从下标为0数的3个字符She用He替换

    string s="Hello! You are nice!";
    char c='h';
    s=s.replace(0,6,5,c);//原串从下标为0的6个字符用5个字符h替换
    cout<<s<<endl;

    string s1="Hello! You are nice!";
    char c1='h';
    s1=s1.replace(0,6,5,c1);//原串从下标为0的6个字符用5个字符h替换
    cout<<s1<<endl;

    string str2="Good morning! Enjoy youself!";
    string s2="A good evening..";
    str2=str2.replace(5,8,s2,7,9);//s2从下标7开始的9个字符来替换s1从下标5开始的8个字符
    cout<<str2<<endl;
    return 0;
}

运行结果:
在这里插入图片描述
永远相信美好🎈

  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

信小海

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

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

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

打赏作者

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

抵扣说明:

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

余额充值