strcat() Function
The strcat()
function concatenates two strings by appending the content of one string to the end of another. This results in a single, combined null-terminated string. The function works by overwriting the null terminator of the first string with the contents of the second, then adding a new null terminator at the end of the combined string.
Syntax of strcat()
char *strcat(char *destination, const char *source);
Parameters
Parameter | Description |
---|---|
destination | Pointer to the destination array, which must contain a null-terminated C string and be large enough to hold the concatenated result. |
source | Pointer to the null-terminated C string that is to be appended to the destination string. |
Return Value
The function returns a pointer to the resulting string, which is the same as the destination string.
Notes
It is important to note that the terminating null character of the first string is overwritten by the first character of the second string during the concatenation process, and a new null terminator is appended at the end. Also, the memory areas for the two strings should not overlap to avoid undefined behavior.
Examples for strcat()
Example 1: Basic String Concatenation
This example demonstrates how to use strcat()
to append one string to another.
Program
#include <stdio.h>
#include <string.h>
int main() {
char first[50] = "Hello, ";
char second[] = "World!";
// Concatenate second string onto first string
strcat(first, second);
printf("Concatenated string: %s\n", first);
return 0;
}
Explanation:
- A character array
first
is initialized with the string"Hello, "
and has ample space for additional characters. - A second character array
second
is initialized with the string"World!"
. - The
strcat()
function appends the content of the second string to the first. - The resulting concatenated string is printed using
printf()
.
Output:
Concatenated string: Hello, World!
Example 2: Building a Sentence by Concatenation
This example demonstrates how to concatenate multiple strings to form a complete sentence.
Program
#include <stdio.h>
#include <string.h>
int main() {
char sentence[100] = "The quick brown ";
char adjective[] = "fox ";
char verb[] = "jumps over ";
char object[] = "the lazy dog.";
// Concatenate strings to form a full sentence
strcat(sentence, adjective);
strcat(sentence, verb);
strcat(sentence, object);
printf("Full sentence: %s\n", sentence);
return 0;
}
Explanation:
- A character array
sentence
is initialized with the beginning of a sentence and is large enough to hold the full sentence. - Additional strings are concatenated sequentially using
strcat()
to form a complete sentence. - The complete sentence is printed using
printf()
.
Output:
Full sentence: The quick brown fox jumps over the lazy dog.