1. 常用方法
a) public String replace(char oldChar, char newChar) (文本)
b) public String replace(CharSequence target, CharSequence replacement)(文本)
c) public String replaceAll(String regex, String replacement) (表达式)
d) commons-lang-2.1:org.apache.commons.lang.StringUtils(文本)
e) Matcher.replaceAll(String replacement)(表达式)
2. 小误差验证
int count = 10*10000;
String str = "127.0.0.1";
{
System.out.print(str.replace('.', '_'));
long b = System.nanoTime();
for (int i = 0; i < count; i++) {
str.replace('.', '_');
}
System.out.println(" basic-char :"+(System.nanoTime()-b));
}
{
System.out.print(str.replace(".", "_"));
long b = System.nanoTime();
for (int i = 0; i < count; i++) {
str.replace("\\.", "_");
}
System.out.println(" CharSequence:"+(System.nanoTime()-b));
}
{
System.out.print(str.replaceAll("\\.", "_"));
long b = System.nanoTime();
for (int i = 0; i < count; i++) {
str.replaceAll("\\.", "_");
}
System.out.println(" replaceAll :"+(System.nanoTime()-b));
}
{
//commons-lang-2.1:org.apache.commons.lang.StringUtils
System.out.print(StringUtils.replace(str, ".", "_"));
long b = System.nanoTime();
for (int i = 0; i < count; i++) {
StringUtils.replace(str, ".", "_");
}
System.out.println(" StringUtils :"+(System.nanoTime()-b));
}
{
Matcher m = Pattern.compile(".", Pattern.LITERAL).matcher(str);
System.out.print(m.replaceAll("_"));
long b = System.nanoTime();
for (int i = 0; i < count; i++) {
m.reset();
m.replaceAll("_");
}
System.out.println(" *CharSequence:"+(System.nanoTime()-b));
}
{
Matcher m = Pattern.compile("\\.").matcher(str);
System.out.print(m.replaceAll("_"));
long b = System.nanoTime();
for (int i = 0; i < count; i++) {
m.reset();
m.replaceAll("_");
}
System.out.println(" *REGEXP :"+(System.nanoTime()-b));
}
3. 鲁莽结论
输出
127_0_0_1 basic-char :9919554
127_0_0_1 CharSequence:73282416
127_0_0_1 replaceAll :209326220
127_0_0_1 StringUtils :69380801
127_0_0_1 *CharSequence:160218838
127_0_0_1 *REGEXP :158787441
127_0_0_1 CharSequence:73282416
127_0_0_1 replaceAll :209326220
127_0_0_1 StringUtils :69380801
127_0_0_1 *CharSequence:160218838
127_0_0_1 *REGEXP :158787441
结论
basic-char >> (StringUtils ≈ CharSequence)>> REGEXP >replaceAll
4. 注意事项
参数为正则表达式的时候,需要字符转义,如 ^.$?*+等