Pages

Friday 4 July 2014

C – strcpy() function

  • strcpy( ) function copies contents of one string into another string. Syntax for strcpy function is given below.
char * strcpy ( char * destination, const char * source );
  • Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
  • If destination string length is less than source string, entire source string value won’t be copied into destination string.
  • For example, consider destination string length is 20 and source string length is 30. Then, only 20 characters from source string will be copied into destination string and remaining 10 characters won’t be copied and will be truncated.

Example program for strcpy( ) function in C:

    • In this program, source string “computerscience” is copied into target string using strcpy( ) function.
#include <stdio.h>
#include <string.h>

int main( )
{
   char source[ ] = "computerscience" ;
   char target[20]= "" ;
   printf ( "\nsource string = %s", source ) ;
   printf ( "\ntarget string = %s", target ) ;
   strcpy ( target, source ) ;
   printf ( "\ntarget string after strcpy( ) = %s", target ) ;
   return 0;
}

Output:

source string = computerscience
target string =
target string after strcpy( ) = computerscience

0 comments:

Post a Comment