In the last tutorial we discussed strcat() function, which is used for concatenation of one string to another string. In this guide, we will see a similar function strncat(), which is same as strcat() except that strncat() appends only the specified number of characters to the destination string.
C strncat() Function Declaration
char *strncat(char *str1, const char *str2, size_t n)
str1 – Destination string.
str2 – Source string which is appended at the end of destination string str1.
n – number of characters of source string str2 that needs to be appended. For e.g. if this is 5 then only the first 5 characters of source string str2 would be appended at the end of destination string str1.
Return value:
This function returns the pointer to the destination string str1.
Example: strncat() Function in C
#include <stdio.h> #include <string.h> int main () { char str1[50], str2[50]; //destination string strcpy(str1, "This is my initial string"); //source string strcpy(str2, ", add this"); //displaying destination string printf("String after concatenation: %s\n", strncat(str1, str2, 5)); // this should be same as return value of strncat() printf("Destination String str1: %s", str1); return 0; }
Output:
String after concatenation: This is my initial string, add Destination String str1: This is my initial string, add
As you can see that only 5 characters of string str2 are concatenated at the end of string str1 because we have specified the count as 5 in the strncat() function.
Another important point to note here is that this function returns the pointer to the destination string, which is why the when we displayed the returned value of strncat(), it is same as the destination string str1
Leave a Reply