在JDK1.4中使用replace(CharSequence target, CharSequence replacement)
JDK1.5中
String | replace(CharSequence target,CharSequence replacement) 使用指定的字面值替换序列替换此字符串匹配字面值目标序列的每个子字符串 |
而JDK1.4无此方法,只有:
String | replaceAll(String regex,String replacement) Replaces each substring of this string that matches the given regular expression with the given replacement. |
查看JDK1.5的代码中replace(CharSequence target,CharSequence replacement) 的实现方式
- public String replace(CharSequence target, CharSequence replacement) {
- return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
- this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
- }
其中Pattern.LITERAL在JD1.4中未实现,且涉及Pattern中的多处代码,不能直接替换。后来查询资料,发现在JDK1.5中存在两个方法:
static String | quote(String s) 返回指定 String 的字面值模式 String 。 |
以及:
|
|
但因为对正则表达式理解不足,均未成功(知道的兄弟可以告诉一声:));且Pattern中的static String
quote(String s)结果出来后还需要调用Pattern中的此方法private void RemoveQEQuoting()进行还原
中的StringUtils已经实现此功能:最终考虑自己写一个,但是检查发现在apache commons-lang
static String | replace(String text, String searchString, String replacement) Replaces all occurrences of a String within another String. |
代码如下:
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
public static String replace(String text, String searchString, String replacement, int max) {
if (isEmpty(text) || isEmpty(searchString) || replacement == null) {
return text;
}
int start = 0;
int end = text.indexOf(searchString, start);
if (end == -1) {
return text;
}
int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = (increase < 0 ? 0 : increase);
increase *= 16;//此处没理解,为什么还要扩大StringBuffer
StringBuffer buf = new StringBuffer(text.length() + increase);
while (end != -1) {
buf.append(text.substring(start, end)).append(replacement);
start = end + replLength;
end = text.indexOf(searchString, 2);
}
buf.append(text.substring(start));
return buf.toString();
}