How can we trim a StringBuilder value without the overhead caused by using StringBuilder.toString().trim() and thereby creating a new String and/or a new StringBuilder instance for each trim call?
How can we trim a StringBuilder value without the overhead caused by using StringBuilder.toString().trim()
Share
trim()semantics and signature is a poor fit for mutable strings, though that is debatable.Either way, the answer is not relevant to solving your problem.
The simplest way is to use
StringBuilder.toString().trim()…In that case, so you need to do what
trim()does under the covers: match and remove the leading and trailing white-space. Since theStringBuilderAPI has no regex support, you’ll need to do this that hard way; i.e. by iterating the characters from the front forward and end backward to see what characters need to be removed, etcetera.Are you sure you wouldn’t prefer to do it the easy way? If not, this Q&A has some example implementations, analysis, benchmarking, etcetera:
Finally, you could implement your own variation of the
StringBuilderclass that does have atrim()method. You could possibly use a different internal representation so that operations that remove characters at the start don’t copy characters. (I would not recommend this … but it is an option if you have a pragmatically strong need fortrim().)The flip-side is that removing characters from the start of a
StringBuilderentails copying all of the remaining characters.Maybe you would be better off turning the complete
StringBuilderinto aStringto start with, then when you usetrim()andsubstring()and the like, you won’t be copying characters2.1 – To the people who claim it is "not constructive" to say this, the alternative is to pretend that we were in the room when the design decisions were made and we did hear the debate that occurred. But that would be a lie. Frankly, it is constructive to point out that nobody here knows the answer, and not pretend otherwise. Why? Because a lot of readers will not be aware that the Java design processes at that time were opaque.
2 – Prior to Java 7, these methods work by creating a new String that shares the backing array of the original
String… so you only end up copying the string’s control information. In Java 7 they changed the implementation oftrimandsubstringso that they used a String constructor that copies a subarray of the backing array.