This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java Strings

 
Lucky Singh
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • 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?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • 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.
 
Niki Nono
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic