C strncat function adds two string together

Syntax

C strncat function has the following format.

char *strncat(char *str1, const char *str2, size_t count);

C strncat function is from header file string.h.

Description

C strncat function concatenates not more than count characters of *str2 to *str1 and terminates str1 with a null. It returns *str1.

You have to ensure that str1 is large enough to hold both its str1 and str2.

Example

Use C strncat function to append two string together.


#include <stdio.h>
#include <string.h>
/* w w  w .ja v  a 2  s . c  o  m*/
int main(void)
{
  char s1[80], s2[80];
  unsigned int len;

  gets(s1);
  gets(s2);


  len = 79-strlen(s2);
  strncat(s2, s1, len);
  printf(s2);

  return 0;
}

The code above generates the following result.


Using strcat and strncat


#include <stdio.h>
#include <string.h>
/* www.j  a va2s  . c  o m*/
int main()
{ 
   char s1[ 20 ] = "Happy "; 
   char s2[] = "New Year ";  
   char s3[ 40 ] = "";       
   
   printf( "s1 = %s\ns2 = %s\n", s1, s2 );

   printf( "strcat( s1, s2 ) = %s\n", strcat( s1, s2 ) );

   printf( "strncat( s3, s1, 6 ) = %s\n", strncat( s3, s1, 6 ) );

   printf( "strcat( s3, s1 ) = %s\n", strcat( s3, s1 ) );

   return 0;

}

The code above generates the following result.





















Home »
  C Language »
    Function Reference »




assert.h
ctype.h
math.h
setjmp.h
signal.h
stdio.h
stdlib.h
string.h
time.h
wctype.h