strcat() Function Tutorial In C and C++ with Examples – POFTUT

strcat() Function Tutorial In C and C++ with Examples


strcat() function is mainly used to copy or add string or char arrays in C and C++ programming languages. In general strcat() function will copy or add given string or char array into the destination string or char array.

strcat() Function Syntax

The strcat() function has the following syntax. The strcat() function is provided by <string.h> library or header.

char *strcat(char *DESTINATION, const char *SOURCE);
  • `char *strcat` is the function where it will return a char pointer. This returns a pointer to the DESTINATION.
  • `char *DESTINATION`  is the character array or string where the SOURCE will be copied or added.
  • `const char *SOURCE` is the character array or string which will be copied or added into DESTINATION.

Copy String with strcat() Function

We will start with a simple example where we will copy the character array str into the dst string. In this example, we will copy or add the Poftut.com into the end of the I love the string which is defined with dst.  Then we will print the dst variable with the puts() function.

/* strcat example */
#include <stdio.h>
#include <string.h>

int main ()
{
   char dst[20]="I love the ";
   char src[20]="Poftut.com";

   strcat(dst,src);

   puts(dst);

   return 0;
}

strcat() vs strncat()

There is also a similar function named strncat() which will copy or add the specified number of characters from the given string. Let’s compare the syntax where we will also provide the number of the characters in the strncat() function.

char *strncat(char *dest, const char *src, size_t n);
  • `char *strncat` is the function where it will return a char pointer.
  • `char *DESTINATION`  is the character array or string where the SOURCE will be copied or added.
  • `const char *SOURCE` is the character array or string which will be copied or added into DESTINATION.
  • `size_t n` is the count of the characters where it can be a byte, integer or long number.
LEARN MORE  Append() Function Examples For Python, JavaScript, and jQuery

Leave a Comment