开发者

Replacing one string with other in C

开发者 https://www.devze.com 2023-04-05 09:34 出处:网络
I have a string {&quot;status&quot;:true} I want to replace &开发者_开发问答quot with \". I tried several string operations, but they\'re not working. #include <stdio.h>

I have a string

{&quot;status&quot;:true}

I want to replace &开发者_开发问答quot with ". I tried several string operations, but they're not working.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *replace (char *this, char *withthat, char *inthis) {
    char *where = inthis;
    if(strlen(withthat)>strlen(this)) {
        fprintf(stderr, "replace can only shrink\n");
        exit(EXIT_FAILURE);
    }
    while ((where = strstr(where, this))) {
        memcpy(where, withthat, strlen(withthat));
        memmove(where+strlen(withthat),where+strlen(this), strlen(where+strlen(this))+1);
    }
    return inthis;
}

int main(void) {
    char string[] = "{&quot;status&quot;:true}";
    printf("%s\n", replace("&quot;", "\"", string));
    return 0;
}

Output:

{"status":true}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号