C Copying String
This string is used to copy the contents of one string into another. strcpy() function copies source string in destination. The base addresses of the source and target strings should be supplied to this function.
Syntax for strcpy():
1 |
strcpy(destination,source); |
Example:
1 2 3 4 5 6 7 8 9 10 11 |
#include<stdio.h> #include<string.h> #include<ctype.h> int main() { char src[]="hello"; char desc[20]; strcpy(desc,src); printf ( "source string = %s\n", src ) ; printf ( "destination string = %s", desc ) ; } |
Output:
1 2 |
source string = hello destination string = hello |
strcpy() copy character into destination string till it doesn’t encounter the end of source string (‘\0’).It is necessary that destination string is big enough to hold the string is copied into it.
C strncpy()
This strncpy() function is used to copy some portion of one string into another string. Copies a given number of characters from destination string to source string.
Syntax for strncpy()
1 |
strncpy(destination,source,number_of_characters); |
Example
1 2 3 4 5 6 7 8 9 10 11 12 |
#include<stdio.h> #include<string.h> #include<ctype.h> int main() { char src[5]="hello"; char desc[3]; strncpy(desc,src,3); printf ( "source string = %s\n", src ) ; *(desc+3)='\0';// Adding null character in String printf ( "destination string = %s", desc ) ; } |
Output:
1 2 |
source string = hello destination string = hel |