Reputation: 90180
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?
Upvotes: 2
Views: 8118
Reputation: 308269
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 String
s instead.
When handling huge string-like objects and doing lots of replace operations, then a specialized API like Ropes for Java could be used.
Upvotes: 4
Reputation: 1377
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).
Upvotes: 0