//刚写的code,测试通过,用C++写的
//如果有疑问,欢迎交流
//如果source里有多个str_s
字串,那么都会将其替换掉
//这里的条件逻辑,可能有点儿复杂,设定一些状态,用flag表示
//flag: 0表示要往tmp_source里插入字符
//flag: 1表示当前找到了可能是str_s的字串
#include<iostream>
#include<string>
using namespace std;
#define N 1000
void repstr(char * source, char * str_s, char * str_d){
int src_len = strlen(source);
char *tmp_source = new char[N]; //创建一个新串,保存替换后的结果
int flag = 0;
int cur_idx = 0, str_d_idx = 0, str_s_idx = 0, tmp_idx = 0;
while(source[cur_idx] != '\0'){
if(flag == 0 && source[cur_idx] == str_s[0]){
flag = 1;
str_s_idx++;
cur_idx++;
}
if(flag == 1){
if(str_s[str_s_idx] == '\0'){
str_d_idx = 0;
//
while(str_d[str_d_idx]!='\0'){
tmp_source[tmp_idx] = str_d[str_d_idx];
tmp_idx++;
str_d_idx++;
}
str_s_idx = 0;
flag = 0;
}else if(str_s[str_s_idx] == source[cur_idx]){
str_s_idx++;
cur_idx++;
}else if(str_s[str_s_idx] != source[cur_idx]){
flag = 0;
cur_idx = cur_idx - str_s_idx;
str_s_idx = 0;
}
}
if(flag == 0&&source[cur_idx]!='\0'){
tmp_source[tmp_idx] = source[cur_idx];
tmp_idx++;
cur_idx++;
}
}
tmp_source[tmp_idx] = '\0';
tmp_idx = 0;
while(tmp_source[tmp_idx]!='\0'){
source[tmp_idx] = tmp_source[tmp_idx];
tmp_idx++;
}
source[tmp_idx] = 0;
delete tmp_source;
}
int main(){
char source[1000] = "word hellonicehelotoyouhellowhy";
cout<<source<<endl;
char *src_s = "hello";
char *tar_s = "ChinaFootball";
repstr(source, src_s, tar_s);
cout<<source<<endl;
return 0;
}