jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes Java Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java Strings" Watch "Java Strings" New topic
Author

Java Strings

Lucky Singh
Ranch Hand

Joined: Jan 19, 2004
Posts: 125
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

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Niki Nono
Ranch Hand

Joined: Mar 20, 2005
Posts: 256
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.


Life called,so here I am.<br />Cheers<br />Niki.:-)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java Strings