How To Concatenate Two Strings In C++

In C++, there are many ways to concatenate two strings. Here I am going to show you some of the best ways of concatenating strings with the example. So without wasting your time let’s start.

Using ‘+’ Operator:

‘+’ operator is widely used in C++. ‘+’ operators works like operator overloading. When operands are int it adds the int and when operands are string it append the second operand to first operand.

int a = 2 + 3; [5]

string a = “geeks”+string(“to”)+string(“code”);[geekstocode]

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

int main() 
{ 
    

	// Appending the string. 
	string a = "geeks"+ string("to") + string("code");

	cout << a << endl; 
	return 0; 
} 

Run Code

Note: You can not use ‘+’ operator like string a = “geeks”+”to”+”code”; because There is no definition of operator + that takes two char*s (in fact, the language doesn’t permit you to write one). As a result, on my compiler this produces a “cannot add two pointers” error. More detailed explanation on StackOverflow

Using append() function

append() function provide you a better way of concatenating two string. It’s syntax is

string& string::append (const string& str)

str: the string to be appended.
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	string init("geeks"); 
	string add("tocode"); 

	// Appending the string. 
	init.append(add); 

	cout << init << endl; 
	return 0; 
} 

Run Code

Syntax 2:

string& string::append (const string& str, size_type str_idx, size_type str_num)

str : is the string to be appended
str_num : being number of characters
str_idx : is index number.
Returns : *this.

you can pass the starting and ending index of string from where you want to copy.


#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
	string str1("Geeks"); 
	string str2("tocode"); 

	cout << "Without Append " << str1 << endl; 
	
    str1.append(str2, 0, 5); 
	cout << "After Using append() : "; 
	cout << str1; 

	return 0; 
} 

Run Code

The time complexity of the append is unspecified but generally up to linear in the new string length.

Using Strcat() function

This function takes two string and concatenate th Second string to the end of first string.

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

int main() 
{ 
char a[10];
char b[20];
	cin>>a>>b;

	// concatenating the string. 
	strcat(a,b); 

	cout <<a<< endl; 

	return 0; 
} 

Run Code

This is the most used 3 ways of concatenate two strings in c++. Hope you liked it. In case of any doubt please comment or contact us on this page.

Leave a Comment

Your email address will not be published. Required fields are marked *