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?
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
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\"}\"" */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With