Pages

Friday 4 July 2014

C – strncpy() function

  • strncpy( ) function copies portion of contents of one string into another string. Syntax for strncpy( ) function is given below.
char * strncpy ( char * destination, const char * source, size_t num );
  • Example:
strncpy ( str1, str2, 4) – It copies first 4 characters of str2 into str1.
strncpy ( str2, str1, 4) – It copies first 4 characters 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.
  • If you want to copy 25 characters from source string using strncpy( ) function, only 20 characters from source string will be copied into destination string and remaining 5 characters won’t be copied and will be truncated.

Example program for strncpy( ) function in C:

    • In this program, only 5 characters from source string “computerscience” is copied into target string using strncpy( ) 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 ) ;
   strncpy ( target, source, 5 ) ;
   printf ( "\ntarget string after strcpy( ) = %s", target ) ;
   return 0;
}

Output:

source string = computerscience
target string =
target string after strncpy( ) =compu

0 comments:

Post a Comment