Inserting characters into a string

前端 未结 4 1404
误落风尘
误落风尘 2020-12-11 09:22

I want to add \"\" to {\"status\":true} so that the string looks like \"{\"status\":\"true\"}\". How can I insert characters to a stri

4条回答
  •  借酒劲吻你
    2020-12-11 10:11

    Use sprintf().

    const char *source = "{\"status\":\"true\"}";
    
    /* find length of the source string */
    int source_len = strlen(source);
    
    /* find length of the new string */
    int result_len = source_len + 2; /* 2 quotation marks */
    
    /* allocate memory for the new string (including null-terminator) */
    char *result = malloc((result_len + 1) * sizeof(char));
    
    /* write and verify the string */
    if (sprintf(result, "\"%s\"", source) != result_len) { /* handle error */ }
    
    /* result == "\"{\"status\":\"true\"}\"" */
    

提交回复
热议问题