Is there a C++ Standard Template Library class that provides efficient string concatenation functionality, similar to C#'s StringBuilder or Java's StringBuffer?
You can use .append() for simply concatenating strings.
std::string s = "string1";
s.append("string2");
I think you might even be able to do:
std::string s = "string1";
s += "string2";
As for the formatting operations of C#'s StringBuilder
, I believe snprintf
(or sprintf
if you want to risk writing buggy code ;-) ) into a character array and convert back to a string is about the only option.
The C++ way would be to use std::stringstream or just plain string concats
edit: with regards formatting you can do all the same formating on a stream, but not in the same way. or you can use a stongly typed functor which encapsulates this and provides a String.Format like interface e.g. boost::format
I normally use either std::string
or std::stringstream
. I have never had any problems with these. I would normally reserve some room first if I know the rough size of the string in advance.
I have seen other people make their own optimized string builder in the distant past.
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;
}
};
It uses two strings one for the majority of the string and the other as a scratch area for concatenating short strings. It optimise's appends by batching the short append operations in one small string then appending this to the main string, thus reducing the number of reallocations required on the main string as it gets larger.
I have not required this trick with std::string
or std::stringbuffer
. I think it was used with a third party string library before std::string, it was that long ago. If you adopt a strategy like this profile your application first.
answered is right.
The append methods, return *this. It is as efficiently as StringBuilder in Java