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?

- 10,049
- 8
- 47
- 68

- 7,914
- 5
- 28
- 37
-
1May I ask why don't you want to use `StringBuilder.toString().trim()` ? – Kazekage Gaara Jun 19 '12 at 05:06
-
2Actually 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. – Pramod Kumar Jun 19 '12 at 05:09
-
You can use `toString().trim()` as many times as you need. Please edit your question and add your previous comment to clarify. – Martín Schonaker Jun 19 '12 at 05:12
-
If it did have a `trim()` method there would presumably be questions asking why? Not a real question. – user207421 Jun 19 '12 at 08:03
-
@EJP - How do I unlock this question ? I want to add the code to trim a StringBuilder. – Erran Morad Dec 11 '14 at 07:31
-
I made some code to trim a StringBuilder, with test inputs to check the correctness - https://stackoverflow.com/questions/5212928/how-to-trim-a-java-stringbuilder/27417960#27417960 – Erran Morad Dec 11 '14 at 08:04
5 Answers
Why does StringBuilder don't have trim() method
- Because that's the way it was designed. Try asking the designers1.
- Because there is not much call for it.
- Because the String
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 StringBuilder.toString().trim()
...
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:
Finally, you could implement your own variation of the StringBuilder
class that does have a trim()
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 for trim()
.)
Actually i am in a loop where i have to compare this
StringBuilder
string with many other values so if i callStringBuilder.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 trim()
and substring()
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 of trim
and substring
so that they used a String constructor that copies a subarray of the backing array.

- 698,415
- 94
- 811
- 1,216
I don't know what you are trying to achieve, but if you're worried about performance perhaps you could perform the trim as you are appending to the StringBuilder.
stringbuilder.append(string.trim())

- 910
- 1
- 6
- 22
Why does StringBuilder don't have trim() method?
Hmm.. StringBuilder
is like String
, just a little difference that it can be modified after creation else it is same as string.
As stated in above link, The principal operations on a StringBuilder are the append and insert methods. I guess they are proposed to support mutable strings, same as with StringBuffer
. And if you can get things done by a small call to some other method and then desired method then whats the matter. Why you want same implementation in multiple classes.
How can we trim a StringBuilder value?
As said by others stringBuilder.toString().trim();
I don't want to use
StringBuilder.toString().trim()
.
Hmm... matter of choice, any specific reason for this?

- 58,650
- 30
- 162
- 207
-
1Actually 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 – Pramod Kumar Jun 19 '12 at 05:15
-
Use your own `char[]` and delimiters then. Check out `java.lang.String` code. – Martín Schonaker Jun 19 '12 at 05:17
You can convert StringBuilder
instance to string
which later can be trimmed.
sb.toString().trim();//sb is stringBuilder Instance.

- 16,057
- 6
- 39
- 59
Use StringBuilder.toString().trim()
but save it in a variable.
For example:
String myTrimmedString = myStringBuilder.toString().trim();
It doesn't have a trim()
method because it is very easy and somewhat preferred to use immutable objects. Imagine one thread is trimming the StringBuilder
while another is appending to it. Imagine the bugs and weirdness that could cause in your code.
-
2Imagine one thread is trimming the StringBuilder while another is appending to it. This situation can also be occur in append operation while one thread is appending something and one is append something else... so what in that case? it should not support append as well – Pramod Kumar Jun 19 '12 at 05:28
-
@PramodKumar I would imagine the VM only lets one thing write to the char[] at a time. However putting the same restriction on reads would be ridiculous. On a simultaneous read and write I would guess it blocks the read, making this a non-issue. It all depends on implementation of the VM. It is very possible trim() would work fine. It was a hypothetical situation to show how much easier it can be to implement immutable objects. And they use less memory. – iracigt Jun 19 '12 at 05:54
-
1Although your solution is correct, your justification is way off. StringBuilder isn't thread-safe by design*, so, as Pramod Kumar said, **any** concurrent operation on it is dangerous. Anyone who uses a StringBuilder in multiple threads without synchronizing on it needs shooting. StringBuffer is the thread-safe version of StringBuilder, as it uses internal synchronization. *(StringBuilder was introduced into Java for situations where you're certain only one thread will ever access it at a time and so wanted to do without the overhead of syncronization in StringBuffer.) – daiscog Nov 13 '14 at 12:43