C++ Program for String Concatenation
In this tutorial, we will learn how to Concatenate Two Strings entered by the user, in the C++ programming language.
In programming, String Concatenation refers to combining two strings into a single resultant string without modifying each of the individual strings.
It is performed by using the '+' operator in between two strings.
After Concatenation operation, the length of the resultant string is the sum of both the individual strings.
String1 = Study
String2 = tonight
String3 = String1 + String2 = Studytonight
The below code demonstrates its implementation in C++.
//This header file is used to make use of the strncpy() method
using namespace std;
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to Concatenate Two Strings in CPP ===== \n\n";
string s1, s2, s3;
cout << "\n\nEnter the first String without any space : ";
cin >> s1;
cout << "\nEnter the second String without any space : ";
cin >> s2;
cout << "\n\nThe two individual Strings before Concatenation are :\n\n";
cout << "String1 = " << s1 << " and its lenght is " << s1.size() << "\n";
cout << "String2 = " << s2 << " and its lenght is " << s2.size() << "\n\n";
//Performing Concatenation of two strings using the + operator in CPP
s3 = s1 + s2;
cout << "\n\nThe resulting string after the Concatenation of the two strings is :\n\n";
cout << "String3 = String1 + String2\n";
cout << "String3 = " << s3 << " and its lenght is " << s3.size() << "\n\n";
cout << "\nNote: Length of String3 is sum of the individual lengths of both the strings.";
cout << "\n\n";
We hope that this post helped you develop better understanding of the concept of String Concatenation in C++. For any query, feel free to reach out to us via the comments section down below.
Keep Learning : )