将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;
}