I think many of the answers here may be missing a quality method included in StringBuilder
: .delete(int start, [int] end)
. I know this is a late reply; however, this should be made known (and explained a bit more thoroughly).
Let's say you have a StringBuilder table - which you wish to modify, dynamically, throughout your program (one I am working on right now does this), e.g.
StringBuilder table = new StringBuilder();
If you are looping through the method and alter the content, use the content, then wish to discard the content to "clean up" the StringBuilder
for the next iteration, you can delete it's contents, e.g.
table.delete(int start, int end).
start and end being the indices of the chars you wish to remove. Don't know the length in chars and want to delete the whole thing?
table.delete(0, table.length());
NOW, for the kicker. StringBuilders
, as mentioned previously, take a lot of overhead when altered frequently (and can cause safety issues with regard to threading); therefore, use StringBuffer
- same as StringBuilder
(with a few exceptions) - if your StringBuilder
is used for the purpose of interfacing with the user.