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?

Gili
  • 86,244
  • 97
  • 390
  • 689
  • 1
    @Tom: I'd say "potentially huge overhead" if you do many replace() calls and have a huge StringBuilder. In that case I'd suggest using Ropes instead of Strings: http://ahmadsoft.org/ropes/ – Joachim Sauer Sep 14 '09 at 16:00
  • The rope interface doesn't appear to support replacing subsets of content, or any mutability at all, which seems like it defeats the purpose if your goal is to replicate replace functionality in StringBuilder. – Jherico Sep 14 '09 at 16:35
  • 2
    @Joachim: I thought of something similar to Ropes a few years back. I wonder why Sun hasn't bothered replacing their implementation with something similar... – Gili Sep 14 '09 at 16:54

2 Answers2

4

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.

When handling huge string-like objects and doing lots of replace operations, then a specialized API like Ropes for Java could be used.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 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 Sep 14 '09 at 16:56
  • See http://stackoverflow.com/questions/3472663/replace-all-occurences-of-a-string-using-stringbuilder for example implementation – Vadzim Dec 06 '13 at 13:20
0

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
  • 1,379
  • 7
  • 6