Replace和ReplaceAll的差别
先澄清幾個誤區(qū)
1、CharSequence 不是 Char :有些小朋友依據(jù)參數(shù)的類型選擇Replace或ReplaceAll方法
2、Replace 和 ReplaceAll :并非有些小朋友想象的Replace僅僅替代一個出現(xiàn)的字符,ReplaceAll 替換全部字符
3、循環(huán)替換的誤區(qū)
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);
上面?zhèn)未a并不能得到你想要的結(jié)果。
eventJson.replace(entry.getKey(), entry.getValue()); 須要替換成 eventJson = eventJson.replace(entry.getKey(), entry.getValue());
不耐煩的同學(xué)如今一定急著想知道兩者的差別呢,如今開始解說:
你能夠去看看兩個方法的定義:
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 主要是用正則表達(dá)式的子字符串進(jìn)行替換。
我們做個測試看看!
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"));
運行結(jié)果!
ABCDE67890abcdef ABCDE67890abcdef !@OK*()-=Abcd !@#$%^&*()-=Abcd
明顯最后一行替換失敗了,由于有正則表達(dá)式字符。
追求性能的同學(xué)一定會問這兩個方法誰快,這個就留個好奇的你了,呵呵...
這邊沒時間做大量的測試給你求證了,可是給出不嚴(yán)謹(jǐn)?shù)膫€人猜想例如以下:
Replace比ReplaceAll性能略好。
可是有正則匹配的時候你肯定選用ReplaceAll了。
希望有時間的同學(xué)提供性能方面的比較哦!謝謝。
總結(jié)
以上是生活随笔為你收集整理的Replace和ReplaceAll的差别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: instanceof 原理
- 下一篇: 鹿血酒的功效?(鹿茸血酒如何鉴别真假)