是否有c++标准模板库类提供有效的字符串连接功能,类似于c#的StringBuilder或Java的StringBuffer?


当前回答

因为std::string在c++中是可变的,你可以使用它。它有一个+=运算符和一个附加函数。

如果需要附加数值数据,请使用std::to_string函数。

如果你想更灵活地将任何对象序列化为字符串,那么可以使用std::stringstream类。但是你需要实现你自己的流操作符函数,让它与你自己的自定义类一起工作。

其他回答

string在c++中是等价的:它是可变的。

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();

您可以使用.append()简单地连接字符串。

std::string s = "string1";
s.append("string2");

我认为你甚至可以做到:

std::string s = "string1";
s += "string2";

至于c#的StringBuilder的格式化操作,我相信将snprintf(或者sprintf,如果你愿意冒险编写有bug的代码;-))转换成字符数组并转换回字符串是唯一的选择。

c++的方法是使用std::stringstream或者只是简单的字符串连接。c++字符串是可变的,因此连接的性能考虑不是那么重要。

关于格式化,您可以在流上执行所有相同的格式化,但方式不同,类似于cout。或者你可以使用强类型函子封装这个并提供一个String。格式类似于界面,例如boost:: Format

如果必须将字符串插入/删除到目标字符串或长字符序列的随机位置,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.