java.lang.String中的replace方法到底替换了一个还是全部替换了。

你没有看错我说的就是那个最常用的java.lang.String,String可以说在Java中使用量最广泛的类了。
但是我却发现我弄错了他的一个API(也可以说是两个API),这个API是关于字符串替换的。

我的错误见解

之前我一直以为String有个API是这样子的,String replace(String oldString, String newString) 用来替换String中的第一个oldString为newString,这可能和我之前做的东西基本山替换的都是单一的字符串有关吧。
但是当我看到队友写的代码int containStringNumber = string.length() - string.replace("containString", "").length(),我认为containStringNumber的值是0或者1,但是我错了。这个结果可能会大于1的。

实际情况

通过API文档可以看出来String有4个替换方法:

1. String	replace(char oldChar, char newChar)    
    描述:Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
    谷歌翻译:返回使用newChar替换此字符串中所有出现的oldChar而产生的字符串。  
2. String	replace(CharSequence target, CharSequence replacement)  
    描述:Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.    
    谷歌翻译: 将与该文字目标序列匹配的此字符串的每个子字符串替换为指定的文字替换序列。  
3. String	replaceAll(String regex, String replacement)  
    描述:Replaces each substring of this string that matches the given regular expression with the given replacement.
    谷歌翻译:将给定替换的给定正则表达式匹配的此字符串的每个子字符串替换。  
4. String	replaceFirst(String regex, String replacement)
    描述:Replaces the first substring of this string that matches the given regular expression with the given replacement.
    谷歌翻译:将给定替换的给定正则表达式匹配的此字符串的第一个子字符串替换。

是的,String里面根本没有跟那个我自以为是的方法。
第一个方法是替换第一个没错,但是替换的是一个char,不是String这儿也是替换全部的的char类型,不是部分替换。
第二个方法是替换的CharSequence(包括String, StringBuffer, StringBuilder),但是替换的是全部。
第三个replaceAll是替换全部的字符串正则表达式,
第四个是缺实是替换了第一个,但是人家名字写得明明白白的replaceFirst,而且替换的也是正则表达式。

教训与总结

这让我想起来前天的一篇文章《On The Value Of Fundamentals In Software Development 》,英文不好的可以自己翻译下。
我要好好学习Java的API了,白干了四年了,纯属一级菜鸟啊。

posted @ 2019-08-21 15:44  神奇小宝  阅读(10806)  评论(1编辑  收藏  举报