Search code examples
cstring

Inserting char string into another char string


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


Solution

  • 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:

    1. You declare the two strings you will be joining, plus a third string into which you will put them.
    2. You declare an integer to tell the program after how many characters you wish to insert the second string into the first.
    3. The strncpy function copies the first x characters into strC. You have to add the null ('\0') character at the end, otherwise you'll probably get rubbish.
    4. Strcat to copy the second string.
    5. Another strcat to copy the remaining part of the first string (strA + x).

    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.