The strcat() function is used for string concatenation. It concatenates the specified string at the end of the another specified string. In this tutorial, we will see the strcat() function with example.
C strcat() Declaration
char *strcat(char *str1, const char *str2)
This function takes two pointer as arguments and returns the pointer to the destination string after concatenation.
str1 – pointer to the destination string.
str2 – pointer to the source string which is appended to the destination string.
Example: C strcat() 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"); //concatenating the string str2 to the string str1 strcat(str1, str2); //displaying destination string printf("String after concatenation: %s", str1); return(0); }
Output:
String after concatenation: This is my initial string, add this
As you can see that we have appended the string str2 at the end of the string str1. The order in which we pass the arguments to the function strcpy matters, the first argument specifies the output string while the seconds argument specifies the other string which is appended at the end of the output string.
As discussed in the beginning of the post that this function returns the pointer to the destination string. This means that if we display the returned value of this function then it should display the destination string(the string str1 in our example). Lets modify our code little bit to verify this.
#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", strcat(str1, str2)); return(0); }
Output:
String after concatenation: This is my initial string, add this
Leave a Reply