C++ Strings

String Concatenation

The + operator can be used between strings to add them together to make a new string. This is called concatenation:

Example

string n1 = “Hello”;
string n2 = “World”;
string n3 = n1 + n2;

cout << n3<<endl;

Output:
HelloWorld

string n3 = n1 + ” ” + n2;

cout << n3<<endl;

Output:
Hello World

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string n1="Hello";
	string n2="World";
	string n3;
	//1st method
	n3=n1+n2;
	cout<<"First String  "<<n1<<endl;
	cout<<"Second String  "<<n2<<endl;
	cout<<"Concatenated String  "<<n3<<endl;
	//2nd method
	n3=n1+" "+n2;
	cout<<"First String  "<<n1<<endl;
	cout<<"Second String  "<<n2<<endl;
	cout<<"Concatenated String  "<<n3<<endl;
	return(0);
}

Output:

First String Hello
Second String World
Concatenated String HelloWorld

First String Hello
Second String World
Concatenated String Hello World

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string n1,n2,n3;
	cout<<"Enter 1st string ";
	cin>>n1;
	cout<<"Enter 2nd string ";
	cin>>n2;

	//1st method
	n3=n1+n2;
	cout<<"First String  "<<n1<<endl;
	cout<<"Second String  "<<n2<<endl;
	cout<<"Concatenated String  "<<n3<<endl;
	//2nd method
	n3=n1+" "+n2;
	cout<<"First String  "<<n1<<endl;
	cout<<"Second String  "<<n2<<endl;
	cout<<"Concatenated String  "<<n3<<endl;
	return(0);
}

Output:

Enter 1st string hello
Enter 2nd string hi
First String hello
Second String hi

Concatenated String hellohi
First String hello

Second String hi
Concatenated String hello hi