Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting characters into a string

Tags:

c

string

I want to add "" to {"status":true} so that the string looks like "{"status":"true"}". How can I insert characters to a string at specific locations?

I tried strncat(), but wasn't able to get the desired result. I read that you need to create your own function for that. Can anyone show me an example?

like image 379
user537670 Avatar asked Jan 18 '23 17:01

user537670


2 Answers

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

like image 162
evgeny Avatar answered Jan 21 '23 06:01

evgeny


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\"}\"" */
like image 25
Jeff Mercado Avatar answered Jan 21 '23 05:01

Jeff Mercado