• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Replace a substring

 
Doanh Nguyen
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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.
Thanks,
Doanh Nguyen
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
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.
 
tormod eriksen
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote a method for doing this. You can find it in my StringHelper class:
http://ostermiller.org/utils/StringHelper.html
 
Doanh Nguyen
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
Doanh
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic