How can I clear or empty a StringBuilder?

Hans Olsson picture Hans Olsson · Mar 4, 2011 · Viewed 529.8k times · Source

I'm using a StringBuilder in a loop and every x iterations I want to empty it and start with an empty StringBuilder, but I can't see any method similar to the .NET StringBuilder.Clear in the documentation, just the delete method which seems overly complicated.

So what is the best way to clean out a StringBuilder in Java?

Answer

Marcus Frödin picture Marcus Frödin · Mar 4, 2011

Two ways that work:

  1. Use stringBuilderObj.setLength(0).
  2. Allocate a new one with new StringBuilder() instead of clearing the buffer.