How can I copy just a portion of a string?


You can use the standard C library function strncpy() to copy one portion of a string into another string. The strncpy() function takes three arguments: the first argument is the destination string, the second argument is the source string, and the third argument is an integer representing the number of characters you want to copy from the source string to the destination string. For example, consider the following program, which uses the strncpy() function to copy portions of one string to another:

#include <stdio.h>
#include <string.h>
void main(void);
void main(void)
     char* source_str = "THIS IS THE SOURCE STRING";
     char dest_str1[40] = {0}, dest_str2[40] = {0};
     /* Use strncpy() to copy only the first 11 characters. */
     strncpy(dest_str1, source_str, 11);
     printf("How about that! dest_str1 is now: '%s'!!!\n", dest_str1);
     /* Now, use strncpy() to copy only the last 13 characters. */
     strncpy(dest_str2, source_str + (strlen(source_str) - 13), 13);
     printf("Whoa! dest_str2 is now: '%s'!!!\n", dest_str2);

The first call to strncpy() in this example program copies the first 11 characters of the source string intodest_str1. This example is fairly straightforward, one you might use often. The second call is a bit more complicated and deserves some explanation. In the second argument to the strncpy() function call, the total length of the source_str string is calculated (using the strlen() function). Then, 13 (the number of characters you want to print) is subtracted from the total length of source_str. This gives the number of remaining characters in source_str. This number is then added to the address of source_str to give a pointer to an address in the source string that is 13 characters from the end of source_str.

Then, for the last argument, the number 13 is specified to denote that 13 characters are to be copied out of the string. The combination of these three arguments in the second call to strncpy() sets dest_str2 equal to the last 13 characters of source_str.

The example program prints the following output:

How about that! dest_str1 is now: 'THIS IS THE'!!!
Whoa! dest_str2 is now: 'SOURCE STRING'!!!

Notice that before source_str was copied to dest_str1 and dest_st2dest_str1 and dest_str2 had to be initialized to null characters (\0). This is because the strncpy() function does not automatically append a null character to the string you are copying to. Therefore, you must ensure that you have put the null character after the string you have copied, or else you might wind up with garbage being printed.


© 2017