A simple solution to clear a StringBuilder / StringBuffer in Java is calling the setLength(0) method on its instance, which causes its length to change to 0. The setLength() method fills the array used for character storage with zeros and sets the count of characters used to the given length.
StringBuffer: Java is popular. Updated StringBuffer: In the above example, we have used the delete() method of the StringBuffer class to clear the string buffer. Here, the delete() method removes all the characters within the specified index numbers.
The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.
One option is to use the delete method as follows:
StringBuffer sb = new StringBuffer();
for (int n = 0; n < 10; n++) {
sb.append("a");
// This will clear the buffer
sb.delete(0, sb.length());
}
Another option (bit cleaner) uses setLength(int len):
sb.setLength(0);
See Javadoc for more info:
The easiest way to reuse the StringBuffer
is to use the method setLength()
public void setLength(int newLength)
You may have the case like
StringBuffer sb = new StringBuffer("HelloWorld");
// after many iterations and manipulations
sb.setLength(0);
// reuse sb
You have two options:
Either use:
sb.setLength(0); // It will just discard the previous data, which will be garbage collected later.
Or use:
sb.delete(0, sb.length()); // A bit slower as it is used to delete sub sequence.
Avoid declaring StringBuffer
or StringBuilder
objects within the loop else it will create new objects with each iteration. Creating of objects requires system resources, space and also takes time. So for long run, avoid declaring them within a loop if possible.
I suggest creating a new StringBuffer
(or even better, StringBuilder
) for each iteration. The performance difference is really negligible, but your code will be shorter and simpler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With