Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

Java Strings

 
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?
 
(instanceof Sidekick)
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.
 
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!