Problem Statment: Given two Strings concatenate one string to another and print the result.
Examples:
Example 1: Input: str1="Take", str2="uforward" Output: Takeuforward Example 2: Input: str1="comp", str2="uter" Output: computer
Disclaimer: Don’t jump directly to the solution, try it out yourself first.
Solution 1:
The most basic approach would be to reach to the end of the first string. This can be done simply using a for loop or any other loop. Once we reach the end of first string, start traversing the second string and keep appending the elements to the first string.
Note: This would work under the assumption that first string has enough space empty to append the second string.
Pseudo Code:
- We take two strings as input.
- we declare a variable i = 0 and then run a loop from i =0 until we reach the end of the first string and keep increasing i by 1 in each step.
- Now at the end of the loop, i is equal to the length of string + 1
- Now we declare another variable j =0 and run a loop from j =0 to the end of the second string.
- In each iteration, copy or store the character at jth position in the second string to the ith position of the first string.
- Now we print the first string.
Code:
C Program
#include <stdio.h>
int main()
{
char str1[20]="take";
char str2[20]="uforward";
int i=0;
while(str1[i]!='\0')
{
i++;
}
for(int j=0;str2[j]!='\0';j++)
{
str1[i]=str2[j];
i++;
}
str1[i]='\0';
printf("After concatenation, the string would look like: %s", str1);
return 0;
}
Output:
After concatenation, the string would look like: takeuforward
Time Complexity: O(m+n), where m is the length of the first string and n is the length of the second string.
Space Complexity: O(1)
Solution 2:
We can also simply use the in-built library function strcat() to concatenate two strings in C.
Syntax: strcat(str1, str2). The concatenated string gets stored in str1.
Code:
C Programs
#include <stdio.h>
#include<string.h>
int main()
{
char str1[20]="take";
char str2[20]="uforward";
strcat(str1,str2);
printf("After concatenation, the string would look like: %s", str1);
return 0;
}
Output:
After concatenation, the string would look like: takeuforward
Special thanks to Subhrajit Das for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article