Concatenating Two Strings in C
Concatenating two strings means appending one string at the end of another string. In this article, we will learn how to concatenate two strings in C.
The most straightforward method to concatenate two strings is by using strcat() function. Let’s take a look at an example:
#include <stdio.h>
#include <string.h>
int main() {
char s1[] = "Hello ";
char s2[] = "Geeks";
// Concatenate str2 to str1
strcat(s1, s2);
printf("%s\n", s1);
return 0;
}
Output
Hello Geeks
The strcat() function is specifically designed to concatenate two strings. It appends the second string (source string) to the end of the first string (destination string)
Note: The destination string should have enough space to store the concatenated string. Otherwise, a segmentation fault may occur.
There are also a few other methods in C to concatenate two strings. Some of them are as follows:
Table of Content
Using sprintf()
The sprintf() function is used to print / store a formatted string to a string buffer. It can be used for concatenating two strings by using the source string as formatted string and destination string as string buffer.
#include <stdio.h>
int main() {
char s1[20] = "Hello ";
char s2[] = "Geeks";
// Concatenate str1 and str2 using sprintf
sprintf(s1 + strlen(s1), "%s", s2);
printf("%s\n", s1);
return 0;
}
Output
Hello Geeks
Using memmove()
The memmove() function can be used to copy the whole block of memory occupied by source string at the end of destination string effectively concatenating the two strings.
#include <stdio.h>
#include <string.h>
int main() {
char s1[20] = "Hello ";
char s2[] = "Geeks";
// Use memmove to concatenate str1 and str2
memmove(s1 + strlen(s1), s2, strlen(s2) + 1);
printf("%s\n", s1);
return 0;
}
Output
Hello Geeks
Note: The memcpy() function can also be used in place of memmove() if the source and destination string does not overlap.
Manually Using a Loop
Use a loop to copy each character of source string at the end of the destination string. The end of the destination string can be found by using strlen() function.
#include <stdio.h>
#include <string.h>
void concat(char s1[], char s2[]) {
// Go to the end of the string s1
s1 = s1 + strlen(s1);
// Copy characters from s2 to s1 using pointers
while (*s1++ = *s2++);
}
int main() {
char s1[50] = "Hello ";
char s2[] = "Geeks";
concat(s1, s2);
printf("%s\n", s1);
return 0;
}
Output
Hello Geeks