Difference between + operator and append function for string class object in C ++?

We can add two objects of the string class, say

string str1="hello" string str2="world" string final =str1+str2; 

or

 string f=str1.append(str2); 

What is the difference between these two methods? the order in which they add or implement or something else?

+4
source share
4 answers
Operator

will add two lines together and generate a new line with a value. Where the string and concatenation to the end of your string will be taken as append.

 #include <iostream> #include <string> using namespace std; int main () { string str = "Writing"; string str2= " a book"; str.append(str2); cout << str << endl; // "Writing a book" return 0; } 

In addition, append has more features, such as just adding part of this line.

 #include <iostream> #include <string> using namespace std; int main () { string str; string str2="Writing "; string str3="print 10 and then 5 more"; // used in the same order as described above: str.append(str2); // "Writing " str.append(str3,6,3); // "10 " str.append("dots are cool",5); // "dots " str.append("here: "); // "here: " str.append(10,'.'); // ".........." str.append(str3.begin()+8,str3.end()); // " and then 5 more" str.append<int>(5,0x2E); // "....." cout << str << endl; return 0; } 

Read more about append here.

+6
source

Well, obviously str1 has different meanings between the two operations (in the first it remains the same as before, in the second it has the same meaning as f ).

Another difference: str1 + str2 creates a temporary string (the result of concatenation), and then applies operator= . Calling str1.append() does not create a temporary variable.

+2
source

First, operator+ creates a new line, and append modifies an existing one. So, in your examples, the second will change str1 , and the first will not. The append method is closer to += than to + .

+2
source

in the case of the + operator, it will first take the temporary space, then copy the first line in it, and then copy the second line after that, as in append () it directly concatenates the second line after the first line, so append is better from a performance point of view. fewer copy operations

0
source

All Articles