If I have a string x='wow'
in Python, I can concatenate this string with itself using the __add__
function, like so:
x='wow'
x.__add__(x)
'wowwow'
How can I do this in C++?
If I have a string x='wow'
in Python, I can concatenate this string with itself using the __add__
function, like so:
x='wow'
x.__add__(x)
'wowwow'
How can I do this in C++?
Semantically, the equivalent of your python code would be something like
std::string x = "wow";
x + x;
i.e. create a temporary string which is the concatenation of x
with x
and throw away the result. To append to x
you would do the following:
std::string x = "wow";
x += x;
Note the double quotes "
. Unlike python, in C++, single quotes are for single characters, and double-quotes for null terminated string literals.
See this std::string
reference.
By the way, in Python you wouldn't usually call the __add__()
method. You would use the equivalent syntax to the first C++ example:
x = 'wow'
x + x
The __add__()
method is just the python way of providing a "plus" operator for a class.
You can use a std::string
and operator+
or operator+=
or a std::stringstream
with operator <<
.
std::string x("wow");
x = x + x;
//or
x += x;
There's also std::string::append
.
You can use the +
operator to concatenate strings in C++:
std::string x = "wow";
x + x; // == "wowwow"
In Python you can also use +
instead of __add__
(and +
is considered more Pythonic than .__add__
):
x = 'wow'
x + x # == 'wowwow'
Normally, when concatenating two distinct strings, you can simply use operator+=
on the string you want to append to:
string a = "test1";
string b = "test2";
a += b;
Will correctly yield a=="test1test2"
However in this case you can't simply append a string to itself, because the act of appending changes both the source and the destination. In other words, this is incorrect:
string x="wow";
x += x;
Instead, a simple solution is to just create a temporary (verbose for clarity):
string x = "wow";
string y = x;
y += x;
...and then swap it back:
x = y;