C String Copy
Syntax
C strcpy function has the following format.
char *strcpy(char *str1, const char *str2);
Description
C strcpy function copies *str2
into *str1
.
*str2
must be a pointer to a null-terminated string.
C strcpy function returns a pointer to str1
.
Example 1
The following code uses strcpy to copy a string.
#include <string.h>
//www . j a v a 2 s . c om
int main()
{
char name[4];
strcpy(name, "Sam");
return (0);
}
Example 2
#include <stdio.h>
//w w w. j a va2s .c o m
void copy1( char *s1, const char *s2 );
void copy2( char *s1, const char *s2 );
int main()
{
char string1[ 10 ];
char *string2 = "Hello";
char string3[ 10 ];
char string4[] = "Good Bye";
copy1( string1, string2 );
printf( "string1 = %s\n", string1 );
copy2( string3, string4 );
printf( "string3 = %s\n", string3 );
return 0;
}
void copy1( char *s1, const char *s2 )
{
int i;
for ( i = 0; ( s1[ i ] = s2[ i ] ) != '\0'; i++ ) {
;
}
}
void copy2( char *s1, const char *s2 ) {
for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ ) {
;
}
}
The code above generates the following result.