cstringstrncmp

How to copy the string that remains after using strncpy


I am learning C and want to learn how I can copy the remaining characters leftover in the string after using strncpy. I would like to have the string Hello World broken down into two separate lines.

For example:

int main() {
    char someString[13] = "Hello World!\n";
    char temp[13];

    //copy only the first 4 chars into string temp
    strncpy(temp, someString, 4);

    printf("%s\n", temp);          //output: Hell
}

How do I copy the remaining characters (o World!\n) in a new line to print out?


Solution

  • First of all, char someString[13] , you don't have enough space for the string Hello World\n, since you have 13 characters but you need at least size of 14, one extra byte for the NULL byte, '\0'. You better off let the compiler decide the size of the array, wouldn't be prone to UB that way.

    To answer your question, you can just use printf() to display the remaining part of the string, you only need to specify a pointer to the element you want to start at.

    In addition, strncpy() doesn't NULL terminate tmp, you are gonna have to do that manually if you want functions like printf() or puts() to function properly.

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char someString[] = "Hello World!\n";
        char temp[14];
    
        strncpy(temp,someString,4);
    
        temp[4] = '\0'; /* NULL terminate the array */
    
        printf("%s\n",temp);
        printf("%s",&someString[4]); /* starting at the 4th element*/
    
        return 0;
    }