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 string
string 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 string
string firstName = "Theophilus ";
// creating another string
string lastName = "Onyejiaku";
//concatenating the string
string fullName = firstName + lastName;
cout << fullName;
return 0;
}

Explanation

  • In the code above, we create two string variables firstName and lastName.
  • 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.

Free Resources