How can I clear or empty a StringBuilder

You can use Java’s StringBuilder to create and manipulate Strings as follows:

StringBuilder sb = new StringBuilder(); sb.append("Some").append(" ").append("String"); System.out.println(sb.toString()); // "Some String"
Code language: Java (java)

The following three (3) options allow you to clear or empty a StringBuilder.

Option 1 – using setLength

sb.setLength(0);
Code language: Java (java)

Option 2 – reinstantiating

sb = new StringBuilder();
Code language: Java (java)

Option 3 – using delete

sb.delete(0, sb.length());
Code language: Java (java)

Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments