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
In this approach concatenating two strings is to iterate through the characters of the first string and append them to the end of the second string until the null character ('\0') is encountered in the first string.
C Code Implementation:
// 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 provides a built-in function called strcat() from the <string.h> library to concatenate strings. This function takes two arguments: the destination string and the source string to be appended.
C Code Implementation:
// 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
Understanding how to concatenate strings is crucial for manipulating and working with textual data in C programming.
Similar articles:
No comments:
Post a Comment