strncat in C language

The C strncat function is a String Function used to append n number of characters from user-specified string to end of the existing string. The syntax of the strncat in C Programming language is

char *strncat(char *destination, char *source, size_t n);

or we can simply write it as:

strncat(str1, str2, string_size);
  • source: A valid string that you want to append to the destination
  • Destination: This is where the function will append the characters from Source.
  • n: The number of characters that you want to append from Source.

strncat in C language Example

The strncat function used to append the user-specified string to the existing string. This program will help you to understand the strncat with multiple examples.

TIP: You have to include the #include<string.h> header before using this strncat String Function.

/* strncat in C Programming to concatenate strings */
 
#include <stdio.h> 
#include<string.h>

int main()
{
   	char str1[] = "Learn";
   	char str2[] = "Learn";
   
   	char str3[] = " C Programming Language";
   	char str4[] = " at tutorialgateway.org";
	
   	strncat(str1, str3, 40);		
   	printf("\n The Final String after the Concatenation = %s", str1);
   
   	strncat(str2, str3, 10);
   	printf("\n The Final String after the Concatenation = %s", str2);
 	
   	strncat(str3, str4, 19);
   	printf("\n The Final String after the Concatenation = %s", str3);
   	
	getch();
	return 0;
}
 The Final String after the Concatenation = Learn C Programming Language
 The Final String after the Concatenation = Learn C Program
 The Final String after the Concatenation = C Programming Language at tutorialgateway.org

This statement will append all the characters in str3 to str1 because the length of C Programming Language is less than the given size 40.

strncat(str1, str3, 40);

This C strncat function will append the first 10 characters present in str3 to str1 because we are restricting the size to 10.

strncat(str2, str3, 10);

strncat in C Example 2

This program allows the user to enter the source and destination strings. Next, it is going to contact them using strncat function.

/* string strncat in C programming Example */
 
#include <stdio.h> 
#include<string.h>
 
int main()
{
	char str1[100], str2[100];
 
	printf("\n Please Enter First String  : ");
	gets(str1);	
	
	printf("\n Please Enter the String that you want to concat : ");
	gets(str2);	
	
	strncat(str1, str2, 8);
	
 	printf("\n The Final String after the Concatenation = %s", str1);
	
}

Although the given string is a valid one, C strncat function only appended up to Tutorial. It is because we restricted the concatenation function to the first 8 characters.

strncat in C Language 2

Let me change the Size value to 16, and see

 Please Enter First String  : Visit

 Please Enter the String that you want to concat : Tutorial Gateway

 The Final String after the Concatenation = Visit Tutorial Gateway