How to add many strings in c++
If you're trying to append string objects of std::string class, this should work.
string s1 = "string1";
string s2 = "string2";
string s3 = "string3";
string s = s1 + s2 + s3;
OR
string s = string("s1") + string("s2") + string("s3") ...
s = s1 + s2 + s3 + .. + sn;
will work although it could create a lot of temporaries (a good optimizing compiler should help) because it will effectively be interpreted as:
string tmp1 = s1 + s2;
string tmp2 = tmp1 + s3;
string tmp3 = tmp2 + s4;
...
s = tmpn + sn;
An alternate way that is guaranteed not to create temporaries is:
s = s1;
s += s2;
s += s3;
...
s += sn;
First of all, you can do the +sn thing just fine. Though it's going to take exponential quadradic(see comments) time assuming you're using std::basic_string<t>
strings on C++03.
You can use the std::basic_string<t>::append
in concert with std::basic_string<t>::reserve
to concatenate your string in O(n) time.
EDIT: For example
string a;
//either
a.append(s1).append(s2).append(s3);
//or
a.append("I'm a string!").append("I am another string!");