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


当前回答

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

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

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

其他回答

如果必须将字符串插入/删除到目标字符串或长字符序列的随机位置,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++中是等价的:它是可变的。

这个答案最近受到了一些关注。我并不是提倡将其作为一种解决方案(这是我过去在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在c++中是可变的,你可以使用它。它有一个+=运算符和一个附加函数。

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

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

Std::string的+=不能用于const char*(像“string to add”这样的东西似乎是什么),所以使用stringstream是最接近所需的-你只需使用<<而不是+