C++ String Concatenation

String Concatenation

The + operator can be used between strings to add them together to make a new string. This is called concatenation:

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main () {
  string firstName = "Priyanshu";
  string lastName = "Raj";
  string fullName = firstName + lastName;
  cout << fullName;
  return 0;
}


//Output---> PriyanshuRaj

In the example above, we added a space after firstName to create a space between Priyanshu and Raj on output. However, you could also add a space with quotes (" " or ' '):

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main () {
  string firstName = "Priyanshu";
  string lastName = "Raj";
  string fullName = firstName + " " + lastName;
  cout << fullName;
  return 0;
}


//Output---> Priyanshu Raj

Append

A string in C++ is actually an object, which contain functions that can perform certain operations on strings. For example, you can also concatenate strings with the append() function:

Example:

#include <iostream>
#include <string>
using namespace std;
 
int main () {
  string firstName = "Priyanshu ";
  string lastName = "Raj";
  string fullName = firstName.append(lastName);
  cout << fullName;
  return 0;
}

//Output---> Priyanshu Raj

It is up to you whether you want to use + or append(). The major difference between the two, is that the append() function is much faster. However, for testing and such, it might be easier to just use +.

Leave a Reply

Your email address will not be published.