C++ Program to Concatenate Two Strings
In this example, we will learn to concatenate (join) two strings (both string objects and C-style strings).
To understand this example, you should have the knowledge of the following C++ programming topics:
Example 1: Program to Concatenate String Objects
You can concatenate two string objects in C++ using + operator.
#include <iostream>
using namespace std;
int main()
{
string s1, s2, result;
cout << "Enter string s1: ";
getline (cin, s1);
cout << "Enter string s2: ";
getline (cin, s2);
result = s1 + s2;
cout << "Resultant String = "<< result;
return 0;
}
Output
Enter string s1: C++ Programming Enter string s2: is awesome. Resultant String = C++ Programming is awesome.
Example 2: Program to concatenate C-style string
You can concatenate two C-style strings in C++ using strcat()
function.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[50], s2[50];
cout << "Enter string s1: ";
cin.getline(s1, 50);
cout << "Enter string s2: ";
cin.getline(s2, 50);
strcat(s1, s2);
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2;
return 0;
}
Output
Enter string s1: I love Enter string s2: C++ programming s1 = I love C++ programming s2 = C++ programming
Next Example
We hope that this Example helped you develop better understanding of the concept of "Concatenate Two Strings" in C++.
Keep Learning : )
In the next Example, we will learn about C++ Copy Strings
.