Simple string concatenation

If I have the string x='wow' in Python, I can build this string using the __add__ function, for example:

 x='wow' x.__add__(x) 'wowwow' 

How to do this in C ++?

-4
source share
5 answers

Semantically, the equivalent of your Python code will be something like

 std::string x = "wow"; x + x; 

i.e. create a temporary string that is a concatenation of x with x and will discard the result. To add to x , you must do the following:

 std::string x = "wow"; x += x; 

Note double quotes. " Unlike python, in C ++, single quotes for single characters and double quotes for null-terminated string literals.

See the std::string link.

By the way, in Python, you usually do not call the __add__() method. You would use the equivalent syntax for the first C ++ example:

 x = 'wow' x + x 

The __add__() method is just a python way to provide a plus operator for a class.

+7
source

You can use std::string and operator+ or operator+= or std::stringstream with operator << .

 std::string x("wow"); x = x + x; //or x += x; 

There is also std::string::append .

+3
source

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' 
+3
source
 std::string x = "wow" x = x + x; 
+1
source

Usually, when combining two different lines, you can simply use operator+= in the line you want to add:

 string a = "test1"; string b = "test2"; a += b; 

a=="test1test2" correctly return a=="test1test2"

However, in this case, you cannot simply add the line to yourself, because the act of adding changes both the source and destination. In other words, this is not true:

 string x="wow"; x += x; 

Instead, a simple solution is to simply create a temporary (detailed for clarity):

 string x = "wow"; string y = x; y += x; 

... and then change it:

 x = y; 
-2
source

All Articles