Is there a C++ Standard Template Library class that provides efficient string concatenation functionality, similar to C#'s StringBuilder or Java's StringBuffer?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
The Rope container may be worth if have to insert/delete string into the random place of destination string or for a long char sequences. Here is an example from SGI's implementation:
NOTE this answer has received some attention recently. I am not advocating this as a solution (it is a solution I have seen in the past, before the STL). It is an interesting approach and should only be applied over
std::string
orstd::stringstream
if after profiling your code you discover this makes an improvement.I normally use either
std::string
orstd::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.
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
orstd::stringstream
. 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.The C++ way would be to use std::stringstream or just plain string concatenations. C++ strings are mutable so the performance considerations of concatenation are less of a concern.
with regards to formatting, you can do all the same formatting on a stream, but in a different way, similar to
cout
. or you can use a strongly typed functor which encapsulates this and provides a String.Format like interface e.g. boost::formatSince
std::string
in C++ is mutable you can use that. It has a+= operator
and anappend
function.If you need to append numerical data use the
std::to_string
functions.If you want even more flexibility in the form of being able to serialise any object to a string then use the
std::stringstream
class. But you'll need to implement your own streaming operator functions for it to work with your own custom classes.