• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

replace char with string

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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;
sb.replace(end,end+findLength,replace);
}
result = sb.toString();
 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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:
http://ostermiller.org/utils/StringHelper.html
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic