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 b{ "b" };
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
andb
with a separator and a newline:string x{}; x += a + ", " + b + "...