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;
}
This notebook is a collection of code snippets and technical "how to" instructions.
Search This Blog
Java: generic replace all method
by: Zainab Aziz
Subscribe to:
Post Comments (Atom)
Java already has a function that does the exact same thing...
ReplyDeletehttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replace(java.lang.CharSequence,%20java.lang.CharSequence)
That is String.replace(). The link is getting cut off in the on the screen I'm looking at.
ReplyDelete