是否有c++标准模板库类提供有效的字符串连接功能,类似于c#的StringBuilder或Java的StringBuffer?
当前回答
如果必须将字符串插入/删除到目标字符串或长字符序列的随机位置,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.
其他回答
c++的方法是使用std::stringstream或者只是简单的字符串连接。c++字符串是可变的,因此连接的性能考虑不是那么重要。
关于格式化,您可以在流上执行所有相同的格式化,但方式不同,类似于cout。或者你可以使用强类型函子封装这个并提供一个String。格式类似于界面,例如boost:: Format
Std::string的+=不能用于const char*(像“string to add”这样的东西似乎是什么),所以使用stringstream是最接近所需的-你只需使用<<而不是+
您可以使用.append()简单地连接字符串。
std::string s = "string1";
s.append("string2");
我认为你甚至可以做到:
std::string s = "string1";
s += "string2";
至于c#的StringBuilder的格式化操作,我相信将snprintf(或者sprintf,如果你愿意冒险编写有bug的代码;-))转换成字符数组并转换回字符串是唯一的选择。
如果必须将字符串插入/删除到目标字符串或长字符序列的随机位置,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。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();
推荐文章
- 自定义c++分配器的引人注目的例子?
- RAII和c++中的智能指针
- 如何构建和使用谷歌TensorFlow c++ api
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?
- 在STL地图中,使用map::insert比[]更好吗?
- C++ Linux的想法?
- 如何为Fedora安装g++ ?
- Std::cin输入空格?
- c++标准是否要求iostreams的性能很差,或者我只是在处理一个糟糕的实现?
- gcc在哪里查找C和c++头文件?
- 为什么我们需要require require ?
- 解析c++中的命令行参数?
- 我如何在c++中创建一个随机的字母数字字符串?
- c++中的atan和atan2有什么区别?