C++实现——字符串替换

这里写图片描述

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
//字符串的替换
/*
语法:replace(string str, string oldstr, string newstr);
参数:
str:在此源字符串进行替换操作
oldstr:被替换的字符串,不能为空串
newstr:替换的字符串,可以为空串,为空串表示在源字符中删除oldstr
返回值:null
注意:
默认str长度小于1000,如否,重新设定设定tmp大小
需要 string
*/
//注意:在输入的时候 同一个字符串中无空格  以空格来分割两个字符串
//第一种替换字符串的方法用C中的strstr 及C++中的substr
void  replace(string &str, string oldstr, string newstr){
    const char *pos= NULL;
    while ((pos=strstr(str.c_str(), oldstr.c_str()))!=NULL){

        int p = pos - &str[0];
        int oldlen = oldstr.size();
        //截取并替换
        str = str.substr(0, p) + newstr + str.substr(p + oldlen);
    }
}


//第二种替换字符串的方法用replace()

void string_replace(string&s1, const string&s2, const string&s3)
{
    string::size_type pos = 0;
    string::size_type a = s2.size();
    string::size_type b = s3.size();
    while ((pos = s1.find(s2, pos)) != string::npos)
    {
        //调用string自身的替换函数
        s1.replace(pos, a, s3);
        pos += b;
    }
}

//测试函数
int main(){

    string s1, oldstr, newstr;
    while (cin>>s1>>oldstr>>newstr){
        //replace(s1, oldstr, newstr);
        string_replace(s1, oldstr, newstr);
        cout << s1 << endl;
    }

    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值