是否有c++标准模板库类提供有效的字符串连接功能,类似于c#的StringBuilder或Java的StringBuffer?
当前回答
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.
Std::string的+=不能用于const char*(像“string to add”这样的东西似乎是什么),所以使用stringstream是最接近所需的-你只需使用<<而不是+
string在c++中是等价的:它是可变的。
这个答案最近受到了一些关注。我并不是提倡将其作为一种解决方案(这是我过去在STL之前见过的解决方案)。这是一个有趣的方法,如果你在分析你的代码后发现这样做有改进,那么只应该应用在std::string或std::stringstream上。
我通常使用std::string或std::stringstream。我从来没有遇到过任何问题。如果我事先知道弦的大致大小,我通常会先预留一些空间。
在遥远的过去,我见过其他人制作他们自己优化的字符串构建器。
class StringBuilder {
private:
std::string main;
std::string scratch;
const std::string::size_type ScratchSize = 1024; // or some other arbitrary number
public:
StringBuilder & append(const std::string & str) {
scratch.append(str);
if (scratch.size() > ScratchSize) {
main.append(scratch);
scratch.resize(0);
}
return *this;
}
const std::string & str() {
if (scratch.size() > 0) {
main.append(scratch);
scratch.resize(0);
}
return main;
}
};
它使用两个字符串,一个用于字符串的大部分,另一个用作连接短字符串的划痕区域。它通过将短的追加操作批处理在一个小字符串中,然后将其追加到主字符串中来优化追加,从而减少主字符串变大时所需的重新分配数量。
我对std::string或std::stringstream不需要这个技巧。我认为它是在std::string之前与第三方字符串库一起使用的,这是很久以前的事了。如果您采用这样的策略,则首先对应用程序进行概要分析。
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();
推荐文章
- cplusplus.com给出的错误、误解或坏建议是什么?
- 找出质数最快的算法是什么?
- c++枚举类可以有方法吗?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 在函数的签名中添加关键字
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 为什么在标准容器中使用std::auto_ptr<>是错误的?
- 用比较double和0
- 保护可执行文件不受逆向工程的影响?
- 在c++中字符串前面的“L”是什么意思?
- 为什么std::map被实现为红黑树?
- 空括号的默认构造函数