String copy is one of the basic operations in manipulating strings. In this operation, all the characters in the source string, including the null terminator, are copied to the target string making it an exact replica of the source string.
As we already know, we cannot copy a string using an assignment operator, as in str2 = strl. Instead, the C standard library provides the strcpy and strncpy functions to copy a string. The strcpy function copies the entire string, whereas the strncpy function copies at most the first n characters. A typical call to the strcpy function takes the following form:
strcpy (dest , src) ;
This function copies string src to dest including the null terminator and it returns a pointer to dest, which is often ignored, as in the above call. As mentioned before, the array dest must have enough character positions to accommodate string src. Observe that the order of arguments dest and src follows the conventions of assignment operation in which the variable being assigned is on the left hand side.
Example of Copy String
The code given below performs string copy using the strcpy function.
char str1 =”Orange”;
char str2 = “Pineapple”;
printf(“strl: %s str2: %s\n”, strl, str2);
The character arrays strl and str2 can store up to 20 characters and are initialized with strings “Orange” and “Pineapple”, respectively. The strcpy function copies entire string strl to str2, overwriting its contents. Seven characters are copied in this operation, including the null · terminator. Thus, the output of this code is as follows:
str1: Orange str2: Orange
strcpy(first, "Dinesh"); /* Initialize first name */
strcpy(last, "Thakur"); /* Initialize last name */
strcpy(full_name, first); /* full = "Dinesh" */
/* Note: strcat not strcpy */
strcat(full_name, " "); /* full = "Dinesh " */
strcat(full_name, last); /* full = "Dinesh Thakur" */
printf("The full name is %s\n", full_name);