简体   繁体   English

替换字符串中的单个单词

[英]replacing a single word in a string

i have a null terminated and dynamically allocated string called 'text_buff' , which contain's the word "bar". 我有一个空终止且动态分配的字符串,称为“ text_buff”,其中包含单词“ bar”。 i want to replace this word with another word of my choice, that can be longer or shorter than the original one. 我想用我选择的另一个单词替换这个单词,该单词可以比原始单词更长或更短。

here's my code up until now, i can't seem to figure out what am i doing wrong. 到目前为止,这是我的代码,我似乎无法弄清楚我在做什么错。

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

You have the wrong loop condition when inserting the new word: 插入新单词时循环条件错误:

        for (i = 0 ; i < strlen("bar")+1; ++i){
            text_buff[wlocation+i] = toswap[i];
        }

It should be: 它应该是:

        for (i = 0 ; i < strlen(toswap); ++i){
            text_buff[wlocation+i] = toswap[i];
        }

Other than that you are missing error handling. 除此之外,您还缺少错误处理。 If this is a school assignment you can probably manage without error handling, though. 但是,如果这是学校的任务,则可以在没有错误处理的情况下管理。

You forget 1 character for the final '\\0'; 您忘记了最后一个'\\ 0'的1个字符;

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

It should be 它应该是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM