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:
- dest: A pointer to the destination string where the source string will be appended.
- src: A pointer to the source string that will be appended to the destination string.
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:
- We define two strings:
str1
with the value "Hello, " andstr2
with the value "World!". - We use the
strcat()
function to append the contents ofstr2
to the end ofstr1
. - The resulting concatenated string is then printed to the console as "Hello, World!".
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
- The
strcat()
function modifies the destination string by appending the source string to it. - The destination string must have enough space to accommodate the source string and the null terminator ('0'). If there is not enough space, it will lead to buffer overflow and undefined behavior.
- It is important to initialize the destination string with enough space, or else you may run into issues when using the function.