I know we can append strings using StringBuilder. Is there a way we can prepend strings (ie: Add strings infront of a string) using StringBuilder so we can keep the performance benefits that StringBuilder offers?
Using the Insert method with the position parameter set to 0 would be the same as preappending.
This goes for C#, but I am sure Java StringBuilder has a similar method.
StringBuilder str = new StringBuilder();
str.Insert(0, "text");
Edit:formated code
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 I understand you correctly, the insert method looks like it'll do what you want. Just insert the string at offset 0.
You could try an extension method:
/// <summary>
/// kind of a dopey little one-off for StringBuffer, but
/// an example where you can get crazy with extension methods
/// </summary>
public static void Prepend(this StringBuilder sb, string s)
{
sb.Insert(0, s);
}
StringBuilder sb = new StringBuilder("World!");
sb.Prepend("Hello "); // Hello World!
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.
I haven't used it but Ropes For Java Sounds intriguing. The project name is a play on words, use a Rope instead of a String for serious work. Gets around the performance penalty for prepending and other operations. Worth a look, if you're going to be doing a lot of this.
A rope is a high performance replacement for Strings. The datastructure, described in detail in "Ropes: an Alternative to Strings", provides asymptotically better performance than both String and StringBuffer for common string modifications like prepend, append, delete, and insert. Like Strings, ropes are immutable and therefore well-suited for use in multi-threaded programming.
You could build the string in reverse and then reverse the result. You incur an O(n) cost instead of an O(n^2) worst case cost.