C string append

后端 未结 10 1292
野趣味
野趣味 2020-12-01 06:21

I want to append two strings. I used the following command:

new_str = strcat(str1, str2);

This command changes the value of str1

10条回答
  •  离开以前
    2020-12-01 06:35

    I write a function support dynamic variable string append, like PHP str append: str + str + ... etc.

    #include 
    #include 
    #include 
    #include 
    
    int str_append(char **json, const char *format, ...)
    {
        char *str = NULL;
        char *old_json = NULL, *new_json = NULL;
    
        va_list arg_ptr;
        va_start(arg_ptr, format);
        vasprintf(&str, format, arg_ptr);
    
        // save old json
        asprintf(&old_json, "%s", (*json == NULL ? "" : *json));
    
        // calloc new json memory
        new_json = (char *)calloc(strlen(old_json) + strlen(str) + 1, sizeof(char));
    
        strcat(new_json, old_json);
        strcat(new_json, str);
    
        if (*json) free(*json);
        *json = new_json;
    
        free(old_json);
        free(str);
    
        return 0;
    }
    
    int main(int argc, char *argv[])
    {
        char *json = NULL;
    
        str_append(&json, "name: %d, %d, %d", 1, 2, 3);
        str_append(&json, "sex: %s", "male");
        str_append(&json, "end");
        str_append(&json, "");
        str_append(&json, "{\"ret\":true}");
    
        int i;
        for (i = 0; i < 10; i++) {
            str_append(&json, "id-%d", i);
        }
    
        printf("%s\n", json);
    
        if (json) free(json);
    
        return 0;
    }
    

提交回复
热议问题