The C strncat function is a String Function used to append n number of characters from a user-specified string to the end of the existing one. The syntax of the strncat in this 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 the Source.
strncat in C language Example
The C strncat function appends the user-specified text to the existing string. This program will help you to understand the strncat with multiple examples.
TIP: You must include the #include<string.h> header before using this strncat String Function.
#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 after the Concatenation = %s", str1); strncat(str2, str3, 10); printf("\n The Final after the Concatenation = %s", str2); strncat(str3, str4, 19); printf("\n The Final after the Concatenation = %s", str3); getch(); return 0; }
The Final after the Concatenation = Learn C Programming Language
The Final after the Concatenation = Learn C Program
The Final 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 of 40.
strncat(str1, str3, 40);
This 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 the strncat function.
#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 valid, the strncat function is only appended up to Tutorial. It is because we restricted the concatenation function to the first 8 characters.
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