我有一个名为 'text_buff' 的空终止和动态分配的字符串,其中包含单词“bar”。我想用我选择的另一个词替换这个词,它可以比原来的更长或更短。
到目前为止,这是我的代码,我似乎无法弄清楚我做错了什么。
char * toswap = "newword";
int diff = strlen(toswap)-strlen("bar");
int wlocation = strstr(text_buff,"bar")-text_buff;
if (diff > 0) {
text_buff = realloc(text_buff,strlen(text_buff)+diff);
for (i=strlen(text_buff) ; i > wlocation+strlen("bar") -1; --i ){
text_buff[i+diff] = text_buff[i];
}
for (i = 0 ; i < strlen("bar")+1; ++i){
text_buff[wlocation+i] = toswap[i];
}
} else if (diff < 0){
for (i=wlocation+diff ; i <strlen(text_buff);++i ){
text_buff[i]=text_buff[i-diff];
}
for (i = 0 ; i < strlen("bar")+1; ++i){
text_buff[wlocation+i] = toswap[i];
}
}