`
sjk2013
  • 浏览: 2183366 次
文章分类
社区版块
存档分类
最新评论

Replace和ReplaceAll的区别

 
阅读更多

先澄清几个误区

1、CharSequence 不是 Char :有些小朋友根据参数的类型选择Replace或ReplaceAll方法

2、Replace 和 ReplaceAll :并不是有些小朋友想象的Replace只替代一个出现的字符,ReplaceAll 替换所有字符

3、循环替换的误区
		String eventJson = ".............";
		Iterator<Entry<String, String>> itPro = map.entrySet().iterator();
		while (itPro.hasNext()) {
			Entry<String, String> entry = itPro.next();
			eventJson.replace(entry.getKey(), entry.getValue());
		}
		System.out.println(eventJson);
上面伪代码并不能得到你想要的结果。

eventJson.replace(entry.getKey(), entry.getValue());
需要替换成
eventJson = eventJson.replace(entry.getKey(), entry.getValue());


不耐烦的同学现在一定急着想知道两者的区别呢,现在开始讲解:

你可以去看看两个方法的定义:

String java.lang.String.replace(CharSequence target, CharSequence replacement)

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
Parameters:
target The sequence of char values to be replaced
replacement The replacement sequence of char values
Returns:
The resulting string
Throws:
NullPointerException - iftarget orreplacement is null.
Since:
1.5

String java.lang.String.replaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use java.util.regex.Matcher.quoteReplacement to suppress the special meaning of these characters, if desired.Parameters:regex the regular expression to which this string is to be matchedreplacement the string to be substituted for each matchReturns:The resulting StringThrows:PatternSyntaxException - if the regular expression's syntax is invalidSince:1.4See Also:java.util.regex.Pattern@specJSR-51

一目了然!

String.Replace 主要是针对字符串的替换。

String.ReplaceAll 主要是用正则表达式的子字符串进行替换。

我们做个测试看看!
		System.out.println("1234567890abcdef".replace("12345", "ABCDE"));
		System.out.println("1234567890abcdef".replaceAll("12345", "ABCDE"));
		System.out.println("!@#$%^&*()-=Abcd".replace("#$%^&", "OK"));
		System.out.println("!@#$%^&*()-=Abcd".replaceAll("#$%^&", "OK"));
执行结果!
ABCDE67890abcdef
ABCDE67890abcdef
!@OK*()-=Abcd
!@#$%^&*()-=Abcd
明显最后一行替换失败了,因为有正则表达式字符!


追求性能的同学一定会问这两个方法谁快,这个就留个好奇的你了,呵呵...

这边没时间做大量的测试给你求证了,但是给出不严谨的个人猜想如下:

Replace比ReplaceAll性能略好。

但是有正则匹配的时候你肯定选用ReplaceAll了。


希望有时间的同学提供性能方面的比较哦!谢谢!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics