Home »
C++ STL
Concatenating two string using + (plus) operator in C++ STL
C++ STL | concatenating two strings: In this article, we are going to see how we can concatenate two strings using (plus) '+' like other default datatypes?
Submitted by Radib Kar, on February 27, 2019
String as datatype
In C, we know string basically a character array terminated by \0. Thus to operate with the string we define character array. But in C++, standard library gives us the facility to use string as a basic data type like integer.
Example:
Like we define and declare,
int i=5,j=7,k;
Same way, we can do for a string like,
string s1="Include", s2="Help";
Now,
k=i+j; // 12
Same way we can concatenate our two string s1 & s2
string s3=s1+s2;
now s3 is "IcludeHelp"
string s4=s2+s1;
s4 is "HelpInclude"
Remember, a string variable (literal) need to be defined under "". 'a' is a character whereas "a" is a string.
Header file needed:
#include <string>
Or
#include <bits/stdc++.h>
C++ program to concatenate strings using plus (+) operator
#include <bits/stdc++.h>
using namespace std;
int main(){
string s1,s2,s3,s4;
cout<<"Enter your string1\n";
cin>>s1;
cout<<"Enter your string2\n";
cin>>s2;
cout<<"Stings concatenated...\n";
s3=s1+s2;
cout<<"Concat(s1,s2): "<<s3<<endl;
s4=s2+s1;
cout<<"Concat(s2,s1): "<<s4<<endl;
return 0;
}
Output
Enter your string1
Include
Enter your string2
Help
Stings concatenated...
Concat(s1,s2): IncludeHelp
Concat(s2,s1): HelpInclude