Pages

Friday 4 July 2014

C – strncat() function

  • strncat( ) function in C language concatenates ( appends ) portion of one string at the end of another string. Syntax for strncat( ) function is given below.
char * strncat ( char * destination, const char * source, size_t num );
  • Example :
strncat ( str2, str1, 3 ); – First 3 characters of str1 is concatenated at the end of str2.
strncat ( str1, str2, 3 ); - First 3 characters of str2 is concatenated at the end of str1.
  • As you know, each string in C is ended up with null character (‘\0′).
  • In strncat( ) operation, null character of destination string is overwritten by source string’s first character and null character is added at the end of new destination string which is created after strncat( ) operation.

Example program for strncat( ) function in C:

    • In this program, first 5 characters of the string “fcomputerscience” is concatenated at the end of the string ”C tutorial” using strncat( ) function and result is displayed as “C tutorial computerscience”.
#include <stdio.h>
#include <string.h>

int main( )
{
   char source[ ] = " computerscience" ;
   char target[ ]= "C tutorial" ;

   printf ( "\nSource string = %s", source ) ;
   printf ( "\nTarget string = %s", target ) ;

   strncat ( target, source, 5 ) ;

   printf ( "\nTarget string after strncat( ) = %s", target ) ;
}

Output:

Source string                       = computerscience
Target string                        = C tutorial
Target string after strcat( ) = C tutorial computerscience

0 comments:

Post a Comment