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了。希望有时间的同学提供性能方面的比較哦!谢谢!
posted on 2017-04-10 17:36 gavanwanggw 阅读(402) 评论(0) 编辑 收藏 举报