我有一个空终止并动态分配的名为'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];
}
}
答案 0 :(得分:2)
插入新单词时出现错误的循环条件:
for (i = 0 ; i < strlen("bar")+1; ++i){
text_buff[wlocation+i] = toswap[i];
}
应该是:
for (i = 0 ; i < strlen(toswap); ++i){
text_buff[wlocation+i] = toswap[i];
}
除此之外,您缺少错误处理。如果这是学校作业,你可以在没有错误处理的情况下进行管理。
答案 1 :(得分:1)
你忘了最后一个'\ 0'的1个字符;
text_buff = realloc(text_buff,strlen(text_buff)+diff);
应该是
text_buff = realloc(text_buff,strlen(text_buff)+diff + 1);