If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, string concatenation is the process of combining two or more strings into one. The strcat()
function is used to concatenate one string to the end of another.
The strcat()
function is implemented in the <string.h>
library. It appends the second string to the end of the first string, including the null character. It returns a pointer to the destination string.
Here is an example of how to use the strcat()
function:
Copy code
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = ", world!";
strcat(str1, str2);
printf("str1: %s", str1);
return 0;
}
In the above example, the content of str2
is concatenated to the end of str1
. The output will be "str1: Hello, world!".
It's important to note that strcat()
function is not secure and should be avoided if you are working with strings that come from an untrusted source. This function can cause a buffer overflow if the destination buffer is not large enough to hold the entire concatenated string, including the null character.
A safer alternative to strcat()
is the strncat()
function. It appends at most n
characters from the second string to the first string, and it does not guarantee that the destination string is null-terminated.
Copy code
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = ", world!";
strncat(str1, str2, sizeof(str1) - strlen(str1) - 1);
printf("str1: %s", str1);
return 0;
}
In this example, strncat()
only appends the characters from str2
to str1
such that it should not exceed the size of str1. The last character of the str1 is set to '\0' so that it can be used as a proper string.
It's also worth noting that, strncat()
is not very efficient in terms of performance, so it is recommended to use it only when you need to concatenate a fixed number of characters from a string.
Comments: 0