C strcat() Function

The strcat() function in C is used to concatenate (join) two strings. It appends the source string (src) to the end of the destination string (dest). The strcat() function is defined in the string.h library.

Syntax of strcat()

The syntax of the strcat() function is as follows:

Syntax:

                        
char *strcat(char *dest, const char *src);
                        
                    

The function takes two arguments:

The function returns a pointer to the destination string (dest) after appending the source string.

Example of strcat() Function

Here is an example that demonstrates how the strcat() function works:

Example:

                        
#include <stdio.h>
#include <string.h>
int main() {
    char str1[50] = "Hello, ";
    char str2[] = "World!";
    
    // Concatenating the strings
    strcat(str1, str2);
    
    // Displaying the concatenated string
    printf("Concatenated String: %s\n", str1);
            
   return 0;
}
                        
                    

Output:

Concatenated String: Hello, World!

Explanation of the Example

In this example:

Example:

                        
#include <stdio.h>
#include <string.h>
int main() 
{
    char firstName[50], lastName[50], fullName[100];
    
    printf("Enter your first name: ");
    fgets(firstName, sizeof(firstName), stdin);
    firstName[strcspn(firstName, "\n")] = '0';  // Remove newline
    
    printf("Enter your last name: ");
    fgets(lastName, sizeof(lastName), stdin);
    lastName[strcspn(lastName, "\n")] = '0';  // Remove newline
    
    strcpy(fullName, firstName);
    strcat(fullName, " ");
    strcat(fullName, lastName);
    
    printf("Your full name is: %s\n", fullName);
    return 0;
}
    
        
                    

Output:

Enter your first name: John Enter your last name: Doe Your full name is: John Doe

Important Notes