This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes replace char with string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "replace char with string " Watch "replace char with string " New topic

replace char with string

peter brews
Ranch Hand

Joined: Jan 25, 2002
Posts: 59
Following piece of code is working only for the first occurence of find string.It is not replacing the second occurence of find string.Could you please help me point out what's worong with this method.
public static String replace(String source,String find,String replace) {
StringBuffer sb = new StringBuffer(source);
int stringLength = source.length();
int start = 0;
int end = 0;
String result="";
int findLength=find.length();

while((end = source.indexOf(find, start)) != -1) {

start = end + findLength;
result = sb.toString();
Steve Deadsea
Ranch Hand

Joined: Dec 03, 2001
Posts: 125
Your algorithm works only if the string you are trying to find is the same length as the string you are replacing it with. Otherwise, sb.replace() alters the length of the stringbuffer and your start and end get messed up.
Instead of altering a stringbuffer, it would be easier if you built a stringbuffer with substrings from the orignal string.
If you haven't already done so, take a look at my implementation of this function in my StringHelper class:
I agree. Here's the link:
subject: replace char with string
jQuery in Action, 3rd edition