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??
Summary. If there are few strings, then you can use any method to append them. From a readability perspective, using + operator seems better for few strings. However, if you have to append a lot of string, then you should use the list and join() function.
The Append operator can have multiple inputs. When one input port is connected, another input port becomes available which is ready to accept another input (if any). This input port expects an ExampleSet. It is output of the Retrieve operator in the attached Example Process.
To append characters, you can use operator +=, append(), and push_back().
The append() Function Amazon Closely related to += operator are the append() functions which allow you to append a string, a character array, or a character to a string. They work like += operator but they are more powerful in that they allow you to, for example, append multiple identical characters of the given count.
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.
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.
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 +
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With