Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
c++

How to concatenate strings using the append function in C++

Onyejiaku Theophilus Chidalu

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 string
  string 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 string
  string firstName = "Theophilus ";

  // creating another string
  string lastName = "Onyejiaku";

  //concatenating the strings
  string fullName = firstName + lastName;
  cout << fullName;
  return 0;
}

Explanation

  • In line 7 & 10, we create two string variables firstName and lastName and we concatenate the two strings using the + operator in line 13.
  • We also assign the output to another variable fullName in 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 variable
  string firstName = "Theophilus ";

  // creating another string variable
  string lastName = "Onyejiaku";

  // using the append() function to add the two strings
  string fullName = firstName.append(lastName);

  cout << fullName;
  return 0;
}
  • In line 7 & 10, we create two string variables firstName and lastName and we concatenate the two strings using the append() function in line 13.
  • We also assign the output to another variable fullName in line 13 which we then print in line 14.

RELATED TAGS

communitycreator
c++

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring