How can we trim a
Why does StringBuilder don't have trim() method
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.
and how can we trim a StringBuilder value?
The simplest way is to use
I don't want 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 the StringBuilder API 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:
Actually i am in a loop where i have to compare this StringBuilder string with many other values so if i call StringBuilder.toString().trim() each time, it will create a new instance and i don't want to create a new String object each time.
The flip-side is that removing characters from the start of a StringBuilder entails copying all of the remaining characters.
Maybe you would be better off turning the complete StringBuilder into a String to start with, then when you use
substring() and the like, you won't be copying characters. (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. UPDATE - In Java 7 they changed the behavior of
substring so that they used a String constructor that copies a subarray of the backing array.)