How can we prepend strings with StringBuilder?

Using the insert method with the position parameter set to 0 would be the same as prepending (i.e. inserting at the beginning).

C# example : varStringBuilder.Insert(0, "someThing");

Java example : varStringBuilder.insert(0, "someThing");

It works both for C# and Java


Prepending a String will usually require copying everything after the insertion point back some in the backing array, so it won't be as quick as appending to the end.

But you can do it like this in Java (in C# it's the same, but the method is called Insert):

aStringBuilder.insert(0, "newText");

If you require high performance with lots of prepends, you'll need to write your own version of StringBuilder (or use someone else's). With the standard StringBuilder (although technically it could be implemented differently) insert require copying data after the insertion point. Inserting n piece of text can take O(n^2) time.

A naive approach would be to add an offset into the backing char[] buffer as well as the length. When there is not enough room for a prepend, move the data up by more than is strictly necessary. This can bring performance back down to O(n log n) (I think). A more refined approach is to make the buffer cyclic. In that way the spare space at both ends of the array becomes contiguous.