...

/

Concatenate Strings

Concatenate Strings

Learn to concatenate strings.

There are several ways to concatenate strings in C++. In this recipe, we will look at the three most common: the string class operator+(), the string class append() function, and the ostringstream class operator<<(). New in C++20, we also have the format() function. Each of these has its advantages, disadvantages, and use cases.

How to do it

In this recipe, we will examine ways to concatenate strings. We will then perform some benchmarks and consider the different use cases.

  • We'll start with a couple of std::string objects:

string a{"a"};
string a{"b"};

Note: The string objects are constructed from literal C-strings.

The C-string constructor makes a copy of the literal string and uses the local copy as the underlying data for the string object.

  • Now, let's construct a new empty string object and concatenate a and b with a separator and a newline:

string x{};
x += a + ", " + b + "\n";
cout << x;

Here, we used the string object's += and + operators to concatenate the a and b strings, along with literal strings ", " and "\n". The resulting string has the elements concatenated together:

a, b
  • We could instead use the string object's append() member function:

string x{};
x.append(a);
x.append(", ");
x.append(b);
x.append("\n");
cout << x;

This gives us the same result:

a, b
  • Or, we could construct an ostringstream object, which uses the stream interface:

ostringstream x{};
x << a << ", " << b << "\n";
cout << x.str();

We get the same result:

a, b
  • We could also use the C++20 format() function:

string x{};
x = format("{}, {}\n", a, b);
cout << x;
...