A string in C++ is used to store text. A string
variable 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, let’s look at the code below.
#include <iostream>// including the string library#include <string>using namespace std;int main() {// creating the stringstring name = "Onyejiaku Theophilus";cout << name;return 0;}
Here we create the string variable called name
and we print it.
Like mentioned earlier, the term string concatenation is a process of adding string
variables together. We simply use the +
operator to add strings together.
#include <iostream>#include <string>using namespace std;int main () {// creating a stringstring firstName = "Theophilus ";// creating another stringstring lastName = "Onyejiaku";//concatenating the stringsstring fullName = firstName + lastName;cout << fullName;return 0;}
firstName
and lastName
and we concatenate the two strings using the +
operator in line 13.fullName
in line 13 which we then print in line 14.The append()
function is also used to add strings together
The syntax is given as:
string.append(string)
The append()
function takes a string
variable as its parameter value.
The append()
function returns a concatenated strings.
#include <iostream>#include <string>using namespace std;int main () {// creating a string variablestring firstName = "Theophilus ";// creating another string variablestring lastName = "Onyejiaku";// using the append() function to add the two stringsstring fullName = firstName.append(lastName);cout << fullName;return 0;}
firstName
and lastName
and we concatenate the two strings using the append()
function in line 13.fullName
in line 13 which we then print in line 14.