Java: generic replace all method

public static String replaceAll(String phrase, String token, String replacement)

    {

if (phrase == null || phrase.length() == 0)

    return phrase;

if (token == null || token.length() == 0)

    throw new IllegalArgumentException("The token you are looking for cannot be empty.");

if (replacement == null)

   replacement = "";

int start = phrase.indexOf(token);

if (start == -1)

    return phrase;

log.warn("Phrase: \"" + phrase + "\" token found at: " + start);

int end = start + token.length();

phrase = phrase.substring(0, start) + replacement + phrase.substring(end, phrase.length());

phrase = replaceAll(phrase, token, replacement);

return phrase;

    }

2 comments:

  1. Java already has a function that does the exact same thing...

    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replace(java.lang.CharSequence,%20java.lang.CharSequence)

    ReplyDelete
  2. That is String.replace(). The link is getting cut off in the on the screen I'm looking at.

    ReplyDelete