Clearing a string buffer/builder after loop

waterfallrain picture waterfallrain · Feb 11, 2010 · Viewed 152.5k times · Source

How do you clear the string buffer in Java after a loop so the next iteration uses a clear string buffer?

Answer

Jon picture Jon · Feb 11, 2010

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: