Ok, so I have a char stringA and char stringB, and I want to be able to insert stringB into stringA at point x.
char *stringA = "abcdef";
char *stringB = "123";
with a product of "ab123cdef"
does anyone know how to do this? Thanks in advance
Ok, so I have a char stringA and char stringB, and I want to be able to insert stringB into stringA at point x.
char *stringA = "abcdef";
char *stringB = "123";
with a product of "ab123cdef"
does anyone know how to do this? Thanks in advance
int insert_pos = 5;
int product_length = strlen(stringA) + strlen(stringB) + 1;
char* product = (char*)malloc(product_length);
strncpy(product, stringA, insert_pos);
product[insert_pos] = '\0';
strcat(product, stringB);
strcat(product, stringA + insert_pos);
...
free(product);
char * strA = "Blahblahblah", * strB = "123", strC[50];
int x = 4;
strncpy(strC,strA,x);
strC[x] = '\0';
strcat(strC,strB);
strcat(strC,strA+x);
printf("%s\n",strC);
Explanation:
Hope that helps.
Remark: remember to make strC long enough to contain both strA and strC, otherwise you'll produce a segmentation fault. You may do this by declaring the string as an array, like in my example.
stringA and stringB are both pointers - they contain the starting address for a blob of memory. The memory they are pointing to contain continuous strings of characters: "abcdef" and "123" respectively. Since strings are contiguous blocks memory (meaning that the memory location of a given character is one byte after the previous) you can't insert more characters into the middle of a string without first moving some characters. In your case you can't even really do this, since the amount of memory allocated for each string is exactly large enough to hold JUST that string (ignoring padding).
What you are going to have to do is copy the strings to another block of memory, one that you have allocated for that purpose, and copy them so that the second string starts x characters into the first string.
Several other SO users have posted code-solutions but I think you should try and find the exact solution on your own (and hopefully my high-level explanation of what's going on will help).