The C library function char *strncat(char *dest, const char *src, size_t n) appends the string pointed to by src to the end of the string pointed to by dest up to n characters long.
An array of characters is called a string.
Declaration
Following is the declaration for an array −
char stringname [size];
For example: char string[50]; string of length 50 characters
Initialization
- Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
- Using string constants −
char string[10] = "Hello":;
Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’.
The strncat( ) function
This is used for combining or concatenating n characters of one string into another.
The length of the destination string is greater than the source string.
The result concatenated string will be in the source string.
The syntax is given below −
strncat (Destination String, Source string,n);
Example
The following program shows the usage of strncat() function −
#include <string.h> main ( ){ char a [30] = "Hello \n"; char b [20] = "Good Morning \n"; strncat (a,b,4); a [9] = "\0"; printf("concatenated string = %s", a); }
Output
When the above program is executed, it produces the following result −
Concatenated string = Hello Good.
Let’s see another example −
Given below is the C program to concatenate n characters from source string to destination string using strncat library function −
#include<stdio.h> #include<string.h> void main(){ //Declaring source and destination strings// char source[45],destination[50]; //Reading source string and destination string from user// printf("Enter the source string :"); gets(source); printf("Enter the destination string before :"); gets(destination); //Concatenate all the above results// destination[2]='\0'; strncat(destination,source,2); strncat(destination,&source[4],1); //Printing destination string// printf("The modified destination string :"); puts(destination); }
Output
When the above program is executed, it produces the following result −
Enter the source string :Tutorials Point Enter the destination string before :Tutorials Point C Programming The modified destination string :TuTur