How to do string concatenation in C++
Overview
A string in C++ is simply used to store text. A string variable is one which contains a collection of characters that are enclosed by double quotes " ".
The process of adding strings together is referred to as string concatenation.
To create a string variable, look at the code below.
Code
#include <iostream>// including the string library#include <string>using namespace std;int main() {// creating the stringstring name = "Onyejiaku Theophilus";cout << name;return 0;}
String concatenation
Like mentioned earlier, the term string concatenation is a process of adding string variables together. We simply use the + operator to add strings together.
Code
#include <iostream>#include <string>using namespace std;int main () {// creating a stringstring firstName = "Theophilus ";// creating another stringstring lastName = "Onyejiaku";//concatenating the stringstring fullName = firstName + lastName;cout << fullName;return 0;}
Explanation
- In the code above, we create two string variables
firstNameandlastName. - We then add the two string variables together using the
+operator and then assign the output to a new variable,fullName, which we print out.