How to concatenate strings using the append function in C++
Overview
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.
Code
#include <iostream>// including the string library#include <string>using namespace std;int main() {// creating the stringstring name = "Onyejiaku Theophilus";cout << name;return 0;}
Explanation
Here we create the string variable called name and we print it.
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 stringsstring fullName = firstName + lastName;cout << fullName;return 0;}
Explanation
- In line 7 & 10, we create two string variables
firstNameandlastNameand we concatenate the two strings using the+operator in line 13. - We also assign the output to another variable
fullNamein line 13 which we then print in line 14.
Using the append() function
The append() function is also used to add strings together
The syntax is given as:
string.append(string)
Parameter
The append() function takes a string variable as its parameter value.
Return value
The append() function returns a concatenated strings.
Code
#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;}
- In line 7 & 10, we create two string variables
firstNameandlastNameand we concatenate the two strings using theappend()function in line 13. - We also assign the output to another variable
fullNamein line 13 which we then print in line 14.