Concatenating Two Strings in C
Given two strings str1 and str2, our task is to concatenate these two strings. There are multiple ways to concatenate two strings in C language:
- Without Using strcat() function
- Using standard method
- Using function
- Using recursion
- Using strcat() function
1. Concatenating Two strings without using the strcat() function
A. Using Standard Method
Input: str1 = "hello", str2 = "world" Output: helloworld Input: str1 = "Geeks", str2 = "World" Output: GeeksWorld
- Get the two Strings to be concatenated
- Declare new Strings to store the concatenated String
- Insert the first string into the new string
- Insert the second string in the new string
- Print the concatenated string
Below is the implementation of the above approach:
First string: Geeks Second string: World Concatenated string: GeeksWorld
B. Using Function
- main function will call concatenate_string() function to concatenate two strings.
- The function will get the length of string s with the help of strlen.
- Now we will append the character of string s1 at s[i+j]. This step will be repeated till no character is available in s1. We are appending characters of string s1 to s from the end of s.
- After for loop, we will be concatenating the string s.
- At last main function will print the string which is concatenated.
Output: Enter the first string: Geeks Enter the second string: forGeeks Concatenated String is: GeekforGeeks
C. Using Recursion
- The function concatenate_string() will get the strings s and s1.
- if no elements are present in s1 then assign s1 with a null (\0) character.
- else if elements are present then we will add the element of string s1 at the end of the string s and will increase the value of i by 1.
- The function concatenate_string will call itself by passing the modified strings s, s1 as arguments. This function will call itself recursively until no elements are available in s1.
Output: Enter the first string: Geeks Enter the second string: forGeeks Concatenated String is: GeeksforGeeks
2. Using strcat() function
strcat() function in C appends the copy of the source string to the destination with a Null character at the end of the string. It comes under string.h header file in C.
Final string is: GeeksforGeeks