Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer does not have replaceAll

 
Em Aiy
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have some template which contains number of repeating characters/expression which are to be replaced at runtime from user input.

Using StringBuffer is better choice to edit the template since it is mutable but to my astonish, it does not has replaceAll method. Why? and what could be the alternate instead of LOOPING!?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Muhammad Ali:
...what could be the alternate instead of LOOPING!?

I would get a String from the StringBuffer, use String's replaceAll method to get a new String, and then make a new StringBuffer.
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
replaceAll() always uses a new StringBuffer behind the scenes to build the new string, so it makes no difference whether the original text is in a String, StringBuffer, or whatever.
 
Em Aiy
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and it does not have replace(String, String) as well .. why!?
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well it isn't hard to implement.
StringBuffer has an indexOf(String str, int start) and a replace(int start, int end, String str). You could implement a replaceAll yourself using those two (not using regexes).
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your assertion that StringBuffer is more efficient than String is incorrect. Suppose you have a string like "xxxxABCxxxxABCxxxx" and you want to replace "ABC" with "DEFGH". Since "DEFGH" is longer than "ABC", you will have to shift the rest of the contents over two spaces before each replacement. If you're working with long strings, that will be way too slow. It's much better to start with a new StringBuffer (or even better, a StringBuilder) and build the new string from scratch. That's how replace(), replaceAll(), trim(), concat(), and all the other "mutating" methods of String work. StringBuffer is not a mutable alernative to String, it's a tool for creating new Strings.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic