As I know that C++ only allows to add 2 strings together, i.e: s = s1 + s2
But I want to be able to add many strings together like:
s = s1 + s2 + s3 + s4 + .... + sn
How could I solve this problem? Can anybody help?
Thanks.
As I know that C++ only allows to add 2 strings together, i.e: s = s1 + s2
But I want to be able to add many strings together like:
s = s1 + s2 + s3 + s4 + .... + sn
How could I solve this problem? Can anybody help?
Thanks.
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!");
If your 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;
std::ostringstream
is build for that, see example here. It's easy:
std::ostringstream out;
out << "a" << "b" << "c" << .... << "z";
std::string str( out.str());