In C programming, concatenating two strings means joining them to create a single string. In this article, we'll explore different approaches to concatenating two strings and provide examples for each method.
Example:
Input: str1 = "Hello" str2 = "World" Output: HelloWorld Input: str1 = "Rahul" str2 = "Sharma" Output: RahulSharm
Approach 1: Using a Loop
// C program to concatenate two string using loop #include <stdio.h> void concatenateStrings(char first[], char second[]) { int i, j; // Find the length of the first string for (i = 0; first[i] != '\0'; i++) {} // Append characters of the second string to the end of the first string for (j = 0; second[j] != '\0'; j++) { first[i + j] = second[j]; } // Add null character to mark the end of the concatenated string first[i + j] = '\0'; } int main() { char first[50] = "Hello "; char second[] = "AlgoLesson"; concatenateStrings(first, second); printf("Concatenated string: %s\n", first); return 0; }
Concatenated string: Hello AlgoLesson
Approach 2: Using strcat() Function
// C program to concatenate two string using strcat function #include <stdio.h> #include <string.h> int main() { char first[50] = "Sharma"; char second[] = "Rahul"; strcat(first, second); printf("Concatenated string: %s\n", first); return 0; }
Concatenated string: SharmaRahul