我有一个空的终止和动态分配的字符串,称为'text_buff',其中包含单词“酒吧”。我想用我选择的另一个词代替这个词,它可以比原来的词更长或更短。替换字符串中的单个字
这是我的代码直到现在,我似乎无法弄清楚我做错了什么。
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];
}
}
以何种方式它不工作? –
@KlasLindbäck它只是纯粹的错误。这个代码只是我在试图解决问题时想到的方向。它只在5个char字符串上工作,但除此之外,它开始覆盖text_buff中的其他单词。 – michel9501
我正在寻找一个适当的解决方案来替换字符串中的单词。 – michel9501