The strcpy()
function copies string2, including the ending null character, to the location that is specified by string1. The strcpy()
function operates on null-ended strings.
Copy String with strcpy()
Function
In this tutorial, you will learn to use the strcpy()
function in C programming to copy strings under the string.h
library.
The structure of strcpy()
function is:
char* strcpy(char* destination, const char* source);
strcpy(destination, source)
is a system defined method used to copy the source string into the destination variable.
Example: With strcpy() function in C
#include <stdio.h> #include <string.h> int main () { char src[50]; char dest[90]; memset(dest, '\0', sizeof(dest)); strcpy(src, "This is techzpad.com c progarm tutorial "); strcpy(dest, src); printf("Our Final copied string : %s\n", dest); return(0); }
Let us compile and run the above program that will produce the following result:
Our Final copied string : This is techzpad.com c progarm tutorial
Copy String without strcpy()
Function
While initializing a string, there is no need to put a null character at the end, as the compiler provides it automatically.
For example, char tpd[] = "TechzPad";
is a correct statement. However while copying one string into another, terminating the destination string with a null character is mandatory, to use it in future.
Example: without strcpy()
function
#include <stdio.h> #include <string.h> int main() { char Str[100]; CopyStr[100]; int i; printf("\n Please Enter any String : "); gets(Str); for (i = 0; Str[i]!='\0'; i++) { CopyStr[i] = Str[i]; } CopyStr[i] = '\0'; printf("\n String that we coped into CopyStr = %s", CopyStr); printf("\n Total Number of Characters that we copied = %d\n", i); return 0; }
Let us compile and run the above program that will produce the following result:
Please Enter Any String: TechzPad String that we coped into CopyStr = TechzPad Total Number of Characters that we copied = 8
Also Read: C Program to Find the Largest Number Among Three Numbers
Leave Your Comment