strncat() and strncpy() string function in C

strncat() and strncpy() are two string functions in C and in this article we will try to explain about them using some C program. So, let’s go ahead to learn strncat() and strncpy() string functions.

strncat() function in C language

strncat() is also a concatenate string function like strcat(). It concatenate n characters of second string to the first string. The null character will always be added to the end of the string. The syntax of strncat() string function is given bellow.

// syntax of strncat() string function

char *strncat(char *firstString, char *secondString, int n);

Let’s see the program bellow to see the use of strncat() function in C.

// strncat() function in C
#include <stdio.h>
#include <string.h>
int main(){
  char firstStr[20] = "Competitive";
  char secondStr[20] = "Programmer";

  strncat(firstStr, secondStr, 3);

  printf("First string after concatenating is : \n%s\n", firstStr);
  return 0;
}

Output of strncat() function program

strncat() function in C

strncpy() function in C language

strncpy() function is used to copy a string to another as like as strcpy() string function. But the difference is that in strcpy() we can copy the entire string to another and here in strncpy() we can copy the required number of characters from the string. Then these characters will replace the first n characters from the first string. The syntax of strncpy() function is like as following.

// syntax of strncpy() function

char *strncpy( char *firstString, char *secondString, size n);

It should be mentioned that if the number of characters n is less than the number of characters in second string then it will copy first n characters from second string to first.

But if the number of characters n is greater than the number of characters of second string then strncpy() function will copy entire second string to the first with the required number of null characters need to fill out taken number n.

Let’s see an example C program using strncpy() function.

// strncpy() function in C
#include <stdio.h>
#include <string.h>
int main(){
  char firstString[30] = "competitive programmer";
  char secondString[30] = "C programming tutorials";

  strncpy(firstString,secondString, 11);    // replace first 11 char from firstString

  printf("First string is : %s\n", firstString);
  return 0;
}

Output of strncpy() function program

strncpy() function in C

Tell us in our discussion section if you have still any doubt about strncat() and strncpy() function.