0

我有一个名为 '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];
                }
}
4

2 回答 2

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

除此之外,您缺少错误处理。但是,如果这是一项学校作业,您可能无需错误处理即可管理。

于 2013-09-27T10:47:16.820 回答
1

您忘记了最后一个 '\0' 的 1 个字符;

text_buff = realloc(text_buff,strlen(text_buff)+diff);

它应该是

text_buff = realloc(text_buff,strlen(text_buff)+diff + 1);
于 2013-09-27T14:01:42.940 回答