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.

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 Articles