aspose file tools*
The moose likes Beginning Java and the fly likes StringBuffer does not have replaceAll Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "StringBuffer does not have replaceAll" Watch "StringBuffer does not have replaceAll" New topic
Author

StringBuffer does not have replaceAll

Em Aiy
Ranch Hand

Joined: May 11, 2006
Posts: 226
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!?


The difference between <b>failure</b> and <b>success</b> is often being <b>right</b> and being <b>exactly right</b>.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Alan Moore
Ranch Hand

Joined: May 06, 2004
Posts: 262
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

Joined: May 11, 2006
Posts: 226
and it does not have replace(String, String) as well .. why!?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19762
    
  20

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).


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Alan Moore
Ranch Hand

Joined: May 06, 2004
Posts: 262
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: StringBuffer does not have replaceAll