Home Java Java-tips Data Strings Q-pr-string-using-loops Programming - Replace method

Ask Questions?

View Latest Questions

Advertisement


 
 

Programming - Replace method
Posted on: July 26, 2006 at 12:00 AM
The predefined Java function replace may not be used for this -- you have to write it yourself.

Java: Programming - Replace method

Change all occurrences in a string

Write a method that replaces all occurrences of one string with another. The predefined Java function replace may not be used for this -- you have to write it yourself.

Example

CallReturnsComments
replace("yesterday", "yes", "no")noterdayOne occurrence replaced.
replace("yesterday", "e", "")ystrdayMany occurrences replaced.
replace("yesterday", "xx", "!")yesterdayNo match, return unchanged.
replace("yesterday", "", "!")yesterdaySpecial case. Better not try to replace "" with anything, otherwise there will be an infinite loop.
replace("xxxxxx", "xx", "x")xxxStart matching after previous replacement.
replace("xxxxxx", "xx", "x")xxxStart matching after previous replacement.
replace("xxxxxx", "xx", "xx")xxxStart matching after previous replacement to avoid infinite loop.
replace("xxxxxx", "x", "xx")xxxStart matching after previous replacement to avoid memory overflow.

Iterative development hints

  1. Write the method header. Should it be static? What type does it return?
  2. Write this method to replace only the first occurrence.
  3. Use a loop to replace all occurrences.
Advertisement


DMCA.com