• 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
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Java Strings

 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a String "predpred". I want to replace the second "red" with "e" and return the new string "predpe".

public String replace(String word, String replace, String replaceWith)
{
///
}

How do I do that?
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As of 1.4 String has a replace method that might do the job for you. If you're on an older JVM that doesn't have replace() the usual trick is:

Do you know the "p" part ahead of time? It's easy to search for "predpred" with indexof. If you also have to handle "gredgred" or "shredshred" then I guess you'd have to search for the "red" only. Find it once, then use that position plus one as a start to find it again.

Play with String.indexof and String.substring and see if you can get something going. Feel free to post more code for comment.
 
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try
String.lastindexOf("red")
but to replace the string you will have to use stans approach.
you will have to play around with String.substring().
try it out and let us know if you have any problems.
 
reply
    Bookmark Topic Watch Topic
  • New Topic