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

Please be polite.

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

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Posts

Most Popular Articles