C

Example Of The C Strncat() Function

In the previous tutorial, we discussed the strcat() function, which is used to concatenate one string to another. In this guide, we’ll look at a function called strncat(), which is similar to strcat() but appends only the specified number of characters to the destination string.

Function Declaration in C strncat()

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

str1 – The target string.
str2 – The source string is appended to the end of the destination string str1.
n – the number of characters from the source string str2 that must be appended. If this is 5, for example, only the first 5 characters of source string str2 are appended to the end of destination string str1.
Value returned:
This function returns the destination string str1 as a pointer.

In C, for example, the strncat() function

#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

Because we specified a count of 5 in the strncat() function, only 5 characters of string str2 are concatenated at the end of string str1.
Another thing to keep in mind is that this function returns a pointer to the destination string, which is why the returned value of strncat() is the same as the destination string str1.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button