3 回答
TA贡献1848条经验 获得超2个赞
也许不如其他方法那么优雅,但是它非常扎实且易于遵循,尤其是。对于刚接触Java的人。让我了解String类的一件事是:它已经存在很长时间了,虽然它支持使用regexp进行全局替换和使用Strings(通过CharSequences)进行全局替换,但最后一个没有简单的布尔参数:'isCaseInsensitive'。确实,您曾想过,只需添加一个小开关,就可以避免它的缺失给初学者带来的所有麻烦。现在在JDK 7上,String 仍然不支持这一功能!
好吧,反正我会停止抓紧。对于特别喜欢Java的每个人,这里都是您可以剪切并粘贴的deus ex machina。就像我说的那样,它不那么优雅,不会赢得任何出色的编码奖,但是它有效并且可靠。任何意见,请随时贡献。(是的,我知道,StringBuffer可能是管理两个字符串突变行的更好选择,但交换技术很容易。)
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's 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;
}
添加回答
举报