Inserting characters into a string

前端 未结 4 1402
误落风尘
误落风尘 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:25

    Yes, you will need to write your own function for that.

    Note that a string in C is a char[], i.e. an array of characters, and is of fixed size.

    What you can do is, create a new string that serves as the result, copy the first part of the subject string into it, append the string that goes in the middle, and append the second half of the subject string.

    The code goes something like,

    // inserts into subject[] at position pos
    void append(char subject[], const char insert[], int pos) {
        char buf[100] = {}; // 100 so that it's big enough. fill with zeros
        // or you could use malloc() to allocate sufficient space
        // e.g. char *buf = (char*)malloc(strlen(subject) + strlen(insert) + 2);
        // to fill with zeros: memset(buf, 0, 100);
    
        strncpy(buf, subject, pos); // copy at most first pos characters
        int len = strlen(buf);
        strcpy(buf+len, insert); // copy all of insert[] at the end
        len += strlen(insert);  // increase the length by length of insert[]
        strcpy(buf+len, subject+pos); // copy the rest
    
        strcpy(subject, buf);   // copy it back to subject
        // Note that subject[] must be big enough, or else segfault.
        // deallocate buf[] here, if used malloc()
        // e.g. free(buf);
    }
    

    Working example here

提交回复
热议问题