替换字符串中连续出现的指定字符串

将str中出现的from的字符串替换成to字符串,如果出现连续from字符串,只替换一个to字符串

str= “123abc”, from = "abc", to = "X"  ---->  str = "123X"

str= “123abcabcd”, from = "abc", to = "X"  ---->  str = "123XXd"


//
//  main.cpp
//  替换字符串中连续出现的指定字符串
//
//  Created by zjl on 16/8/13.
//  Copyright © 2016年 zjl. All rights reserved.
//

#include <iostream>
#include <string>
using namespace std;

string change(string str, string from, string to){
    int pos = 0, match = 0, len = str.size(), len_from = from.size();
    while(pos < str.size()){
        if(str[pos] == from[match++]){
            if(match == len_from){
                str.replace(pos-match+1, match, "*");
                pos -= match;
            }
        }else{
            match = 0;
        }
        pos++;
    }
    int i = 0;
    while(i < str.size()){
        if(str[i] == '*')
            str.replace(i, 1, to);
        i = i + to.size();
    }
    return str;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    string str = "123abcabcd";
    string from = "abc";
    string to = "X";
    string s = change(str, from, to);
    cout << s <<endl;
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值