tags:

views:

230

answers:

2

String contains a bunch of useful methods such as String.replace(CharSequence, CharSequence) that are completely missing from StringBuilder. Is there a reason why?

Is there an easy way to implement these methods without the huge overhead of invoking StringBuilder.toString() which copies the string every time?

+2  A: 

Since StringBuilder provides both indexOf(String,int) and replace(int,int,String) one can easily reproduce the functionality. The only drawback here is that the arguments can't be any CharSequence objects, but must be Strings instead.

Joachim Sauer
indexOf() is defined in terms of toCharArray() and repace() is defined in terms of expandCapacity() and System.arrayCopy(). Neither is likely to be efficient if what the original poster is looking for is something more efficient than just calling StringBuilder.toString().
Jherico
I filed this RFE with Sun: http://bugs.sun.com/view_bug.do?bug_id=6882490
Gili
A: 

Well, Pattern.matcher() takes a CharSequence, so you can do your matching operation against the original builder without copying it to a new String.

as for the replacement, if it is non-trivial (not the same length text), you most likely want to copy to a new StringBuilder anyway (as you would when doing a search/replace using a Matcher). otherwise, you may end up re-copying your data many times over within your original StringBuilder (because any insertion/deletion in the middle of a StringBuilder requires copying the trailing data).

james