Concatenate Two Strings in C
String concatenation is the process of joining two strings together to form a single string. In C programming, this is a common operation used in many applications such as text processing, user input handling, and data formatting.
Unlike some high-level programming languages, C does not support string concatenation using operators like '+'. Instead, strings in C are character arrays, and we need to manually combine them using loops, pointers, or standard library functions.
In this tutorial, you will learn multiple methods to concatenate two strings in C, including manual concatenation using loops, pointer-based techniques, and the use of the built-in strcat() function. Each method will be explained in detail to help you understand how it works internally.
1. Concatenation Using Loop
The most fundamental method of concatenating two strings is by using a loop. In this approach, we first find the end of the first string and then append characters of the second string one by one.
#include <stdio.h>
int main() {
char str1[100], str2[100];
int i = 0, j = 0;
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);
while(str1[i] != '\0') {
if(str1[i] == '\n') {
str1[i] = '\0';
break;
}
i++;
}
while(str2[j] != '\0') {
if(str2[j] != '\n') {
str1[i++] = str2[j];
}
j++;
}
str1[i] = '\0';
printf("Concatenated string: %s", str1);
return 0;
}
This method is simple and gives you full control over how strings are combined. It is especially useful for beginners to understand how strings are stored and manipulated in memory.
2. Step-by-Step Explanation
Let’s assume the first string is "Hello" and the second string is "World".
1. The program first scans the first string to find its null terminator. 2. Once the end is reached, it starts copying characters from the second string. 3. Each character from the second string is appended to the first string. 4. After copying all characters, a null terminator is added at the end. 5. The final string becomes "HelloWorld".
This approach ensures that the second string is appended exactly at the end of the first string without overwriting existing data.
3. Using strcat() Function
C provides a built-in function called strcat() in the
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);
str1[strcspn(str1, "\n")] = '\0';
str2[strcspn(str2, "\n")] = '\0';
strcat(str1, str2);
printf("Concatenated string: %s", str1);
return 0;
}
The strcat() function is convenient and reduces the amount of code you need to write. However, you must ensure that the destination string has enough space to hold the result.
4. Using Pointers
A more advanced method involves using pointers to concatenate strings. This approach is efficient and commonly used in system-level programming.
#include <stdio.h>
int main() {
char str1[100], str2[100];
char *p1, *p2;
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);
p1 = str1;
p2 = str2;
while(*p1 != '\0') {
if(*p1 == '\n') {
*p1 = '\0';
break;
}
p1++;
}
while(*p2 != '\0') {
if(*p2 != '\n') {
*p1 = *p2;
p1++;
}
p2++;
}
*p1 = '\0';
printf("Concatenated string: %s", str1);
return 0;
}
Pointer-based concatenation avoids indexing and can be slightly more efficient. It also helps you understand how memory is accessed directly in C.
5. Using a Third String
Instead of modifying the first string, you can create a third string to store the result. This approach is useful when you want to preserve the original strings.
#include <stdio.h>
int main() {
char str1[100], str2[100], result[200];
int i = 0, j = 0;
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);
while(str1[i] != '\0' && str1[i] != '\n') {
result[i] = str1[i];
i++;
}
while(str2[j] != '\0') {
if(str2[j] != '\n') {
result[i++] = str2[j];
}
j++;
}
result[i] = '\0';
printf("Concatenated string: %s", result);
return 0;
}
This method is safer when you do not want to overwrite the original strings, but it requires additional memory.
6. Common Mistakes
One of the most common mistakes is not allocating enough memory for the destination string. This can lead to buffer overflow and undefined behavior.
Another mistake is forgetting to remove newline characters when using fgets(). This can result in unexpected formatting in the output.
Beginners often forget to add the null terminator after concatenation, which can cause garbage values to appear when printing the string.
Improper pointer handling can also lead to segmentation faults, especially when dealing with pointer-based methods.
7. Best Practices
Always ensure that the destination string has enough space to hold both strings combined.
Use standard functions like strcat() when appropriate, but understand how they work internally.
Remove newline characters when taking input using fgets().
Use clear and meaningful variable names to improve code readability.
Conclusion
Concatenating strings in C is a fundamental operation that helps you understand how strings and memory work together. Unlike high-level languages, C requires manual handling of strings, which gives you greater control but also demands careful programming.
In this tutorial, we explored multiple methods including loop-based concatenation, the strcat() function, pointer-based techniques, and using a third string. Each approach has its own advantages depending on the situation.
By practicing these methods, you will gain confidence in handling strings and be better prepared for more advanced topics such as string parsing, text processing, and file handling in C.
Codecrown