my dog learned polymorphism
The moose likes Beginning Java and the fly likes Replace a substring Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Replace a substring " Watch "Replace a substring " New topic

Replace a substring

Doanh Nguyen
Ranch Hand

Joined: Dec 02, 2000
Posts: 45
I would like to replace ALL occurences of substring a with substring b in a given string. For example:
String s = "12sddddd12xsd";
I woould like to replace "12" with "ABC" so that s will be "ABCsdddddABCxsd" after the substitution.
I found the current String replace() method inadequate for this purpose since it only deals with chars. And StringBuffer lacks indexOf() methods that would identify the position of the substring to be replaced.
Doanh Nguyen
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Strings in Java 1.4 have this ability.
Otherwise, if you were to do a quick search on this forum, I'd bet you'd turn up some useful information as I've noticed this question asked and answered a few times in my short time here. The search page link is at the top right of this page.
Good Luck.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
tormod eriksen
Ranch Hand

Joined: Jan 23, 2002
Posts: 52
I tried to come up with a possible solution which may give you some hints. This is untested.
String replace(String old, String from, String to){
while(old.indexOf != -1){
n = n + old.subString(0, old.indexOf(from)) + to;
old = old.substring(old.indexOf(from) + from.length);
n = n + old;
return n;
Steve Deadsea
Ranch Hand

Joined: Dec 03, 2001
Posts: 125
I wrote a method for doing this. You can find it in my StringHelper class:
Doanh Nguyen
Ranch Hand

Joined: Dec 02, 2000
Posts: 45

Thanks Steve. The StringHelper is a kind of string parser I always wanted but didn't know who to ask. I downloaded the whole utils package.
I agree. Here's the link:
subject: Replace a substring
It's not a secret anymore!