在C中用其他字符串替换一个字符串

时间:2011-09-17 21:48:28

标签: c string

我有一个字符串

{"status":true}

我想将&quot替换为"。我尝试了几个字符串操作,但它们没有工作。

1 个答案:

答案 0 :(得分:1)

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

输出:

{"status":true}