C strcat() and strncat()


In this article, you will learn the concept of C strcat() and strncat() standard library function defined under string handling library <string.h>.

c strcat() and strncat()

C strcat() and strncat() functions

These standard library functions strcat() and strncat() concatenate or joins two strings.

Please visit C programming string to learn more about string.

Function prototype of C strcat() and strncat()

char *strcat( char *str1, const char *str2)
char *strncat( char *str1, const char *str2, size_t n)

where,

             str1 = destination string or character array.

             str2 = source string or character array

When strcat( ) function is executed, string str2 is appended to array str1 and value of str1 is returned.

When strncat function is executed, n characters of string str2 are appended to array str1 and the value of str1 is returned.

In the process, the terminating null character \0 of str1 is replaced by the first character of the str2.

Let’s take a look

c programming strcat

 

C Programming Tips
Make sure that the size of the first character array must be large enough to store the first string, the second string, and the null character.

C program to demonstrate the function of strcat( ) and strncat( )

/*C program to demonstrate the function of strcat and strncat*/

#include<stdio.h>
#include<string.h>

int main()
{
   char str1[ 20 ] = "Hello "; //initialize str1
   char str2[ ] = "World !!! "; //initialize str2
   char str3[ 50 ] = ""; //initialize str3 to empty

   printf("str1 = %s\n\n"
          "str2 = %s\n\n", str1, str2);

   //concatenate str2 to str1
   printf("strcat(str1, str2) = %s\n\n", strcat(str1, str2));

   //concatenate first 6 characters of str2 to str3
   printf("strncat(str3, str2, 6) = %s\n\n", strncat(str3, str2, 6));

   //concatenate str1 to str3
   printf("strcat(str3, str1) = %s\n\n", strcat(str3, str1));

   return 0;
}

Output
strcat strncat output

Explanation

In this program, standard string handling library function strncat is used to copy the first 6 characters of the str2 into str3.

The above program clearly illustrates the concept of the C programming strcat( ) and strncat( ).