You can concatenate std::string
s using the overloaded +
and +=
operators.
Using the +
operator:
std::string hello = "Hello";
std::string world = "world";
std::string helloworld = hello + world; // "Helloworld"
Using the +=
operator:
std::string hello = "Hello";
std::string world = "world";
hello += world; // "Helloworld"
You can also append C strings, including string literals:
std::string hello = "Hello";
std::string world = "world";
const char *comma = ", ";
std::string newhelloworld = hello + comma + world + "!"; // "Hello, world!"
You can also use push_back()
to push back individual char
s:
std::string s = "a, b, ";
s.push_back('c'); // "a, b, c"
There is also append()
, which is pretty much like +=
:
std::string app = "test and ";
app.append("test"); // "test and test"