是否有c++标准模板库类提供有效的字符串连接功能,类似于c#的StringBuilder或Java的StringBuffer?
当前回答
Std::string的+=不能用于const char*(像“string to add”这样的东西似乎是什么),所以使用stringstream是最接近所需的-你只需使用<<而不是+
其他回答
Std::string的+=不能用于const char*(像“string to add”这样的东西似乎是什么),所以使用stringstream是最接近所需的-你只需使用<<而不是+
因为std::string在c++中是可变的,你可以使用它。它有一个+=运算符和一个附加函数。
如果需要附加数值数据,请使用std::to_string函数。
如果你想更灵活地将任何对象序列化为字符串,那么可以使用std::stringstream类。但是你需要实现你自己的流操作符函数,让它与你自己的自定义类一起工作。
std:: string。Append函数不是一个好的选择,因为它不接受很多形式的数据。一个更有用的替代方法是使用std::stringstream;像这样:
#include <sstream>
// ...
std::stringstream ss;
//put arbitrary formatted data into the stream
ss << 4.5 << ", " << 4 << " whatever";
//convert the stream buffer into a string
std::string str = ss.str();
如果必须将字符串插入/删除到目标字符串或长字符序列的随机位置,Rope容器可能是值得的。 下面是一个来自SGI实现的例子:
crope r(1000000, 'x'); // crope is rope<char>. wrope is rope<wchar_t>
// Builds a rope containing a million 'x's.
// Takes much less than a MB, since the
// different pieces are shared.
crope r2 = r + "abc" + r; // concatenation; takes on the order of 100s
// of machine instructions; fast
crope r3 = r2.substr(1000000, 3); // yields "abc"; fast.
crope r4 = r2.substr(1000000, 1000000); // also fast.
reverse(r2.mutable_begin(), r2.mutable_end());
// correct, but slow; may take a
// minute or more.
string在c++中是等价的:它是可变的。