I wish to insert some characters into a string in C:
Example: char string[100] = "20120910T090000";
I want to make it something like "2012-09-10-T-0900-00"
My code so far:
void append(char subject[],char insert[], int pos) {
char buf[100];
strncpy(buf, subject, pos);
int len = strlen(buf);
strcpy(buf+len, insert);
len += strlen(insert);
strcpy(buf+len, subject+pos);
strcpy(subject, buf);
}
When I call this the first time I get: 2012-0910T090000
However when I call it a second time I get: 2012-0910T090000-10T090000
Any help is appreciated
Here’s some working code, which gives me the output:
It uses
memmove()because it is guaranteed that the strings being copied around overlap.Of course, I’m assuming C99 support with the
forloop notation. Note, too, that in classic C style, the code does not take the size of the target string, so it does not ensure that there is no buffer overflow. It wouldn’t be all that hard to add the parameter and do the check; the problem area is how to indicate that the function failed. You could use a different interface to the function, taking arbitrary length strings to be inserted at arbitrary positions; it isn’t significantly harder…