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;

    }



As an Amazon Associate I earn from qualifying purchases.

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

Post Scriptum

The views in this article are mine and do not reflect those of my employer.
I am preparing to cancel the subscription to the e-mail newsletter that sends my articles.
Follow me on:
X.com (Twitter)
LinkedIn
Google Scholar

Popular Recent Posts

Most Popular Articles

apt quotation..