grv
grv

Reputation: 1153

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

We can add two string class object let's 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?? order in which they add or implementation or anything else??

Upvotes: 5

Views: 4264

Answers (4)

Manish Rathi
Manish Rathi

Reputation: 1

in case of + operator it will first take a temporary space then copy the first string in it and then copy the second string afterwards where as in append() it directly concatenate the the second string after first string , so append is better in terms of performance no. of copy operations are less

Upvotes: 0

Caesar
Caesar

Reputation: 9843

operator+ will add two strings together and generate a new string with the value. Where as append will take a string and concatenate to the end of your string.

#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;
}

Also, append has more features like only append a part of that string

#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;
}

More on append here.

Upvotes: 8

juanchopanza
juanchopanza

Reputation: 227468

For one, operator+ creates a new string, whereas append modifies a previously existing one. So, in your examples, the second one will modify str1, and the first one will not. The append method is closer to += than to +.

Upvotes: 2

Vlad Ciobanu
Vlad Ciobanu

Reputation: 1473

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

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

Upvotes: 2

Related Questions