Concatenation of two strings


StringViews 4495

Given a two strings, this function will concatenate the two strings into one string.

Example

INPUT

s1= cat
s2 = dog

OUTPUT

catdog

In the above example, the two strings cat and dog are concatenated

Time Complexity: O(n),

where n is the size of the largest string

Algorthm1

1. Create an empty string named result
2.  Add all the characters of first string to the string result
3. Add all the characters of second string to the string result
4. result contains the concatenation of input strings

C++ Program

#include <bits/stdc++.h>
using namespace std;

int main()
{
	string s1,s2; //two string
	cin>>s1>>s2;
	
	string result;
	for(int i=0;i<s1.size();i++) //add all characters of first string
		result += s1[i];
			
	for(int i=0;i<s2.size();i++)//concat all charcaters of second string
		result += s2[i];
	
	cout<<result;
	
	return 0;
}

Try It

Algorithm 2(STL)

In this algorithm we use the standard template library function We use the function named append to concatenate the input strings ie, s1.append(s2) append function directly appends two strings without using any extra string.

C++ Program

#include <bits/stdc++.h>
using namespace std;

int main()
{
	string s1,s2; //two string
	cin>>s1>>s2;
	
	s1.append(s2); //if no extra string is to be taken
	cout<<s1;
	
	return 0;
}

Try It

Algorithm 3

In this algorithm we use the “+” operator to concatenate the input strings ie, s1 + s2

C++ Program

#include <bits/stdc++.h>
using namespace std;

int main()
{
	string s1,s2; //two string
	cin>>s1>>s2;
	
	string result = s1 + s2;//direct concat using + operator
	
	cout<<result;
	
	return 0;
}

Try It

Translate »