Not as elegant as the other approaches, but it is quite simple and easy to use, especially. for people newer to Java. One thing that calls me in the String class is this: it has been around for a very long time, and although it supports global regex and global strings replacements (via CharSequences), the latter does not have a simple boolean parameter: 'isCaseInsensitive'. In fact, you thought that just adding that one small switch, all the problems associated with its absence for beginners, especially could be avoided. Now on JDK 7 String still does not support this one small addition!
OK, I will stop grabbing. For everyone, particularly newer ones for Java, here is your cut and paste deus ex machina. As I said, itβs not so elegant and will not win any weak prizes for coding, but it works and is reliable. Any comments feel free to contribute. (Yes, I know, StringBuffer is probably the best choice for controlling two mutation lines of a string of characters, but it's fairly easy to exchange techniques.)
public String replaceAll(String findtxt, String replacetxt, String str, boolean isCaseInsensitive) { if (str == null) { return null; } if (findtxt == null || findtxt.length() == 0) { return str; } if (findtxt.length() > str.length()) { return str; } int counter = 0; String thesubstr = ""; while ((counter < str.length()) && (str.substring(counter).length() >= findtxt.length())) { thesubstr = str.substring(counter, counter + findtxt.length()); if (isCaseInsensitive) { if (thesubstr.equalsIgnoreCase(findtxt)) { str = str.substring(0, counter) + replacetxt + str.substring(counter + findtxt.length()); // Failing to increment counter by replacetxt.length() leaves you open // to an infinite-replacement loop scenario: Go to replace "a" with "aa" but // increment counter by only 1 and you'll be replacing 'a forever. counter += replacetxt.length(); } else { counter++; // No match so move on to the next character from // which to check for a findtxt string match. } } else { if (thesubstr.equals(findtxt)) { str = str.substring(0, counter) + replacetxt + str.substring(counter + findtxt.length()); counter += replacetxt.length(); } else { counter++; } } } return str; }
Matt Campbell May 15 '13 at 20:23 2013-05-15 20:23
source share