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。
第二个方法是替换的CharSequence(包括String, StringBuffer, StringBuilder),但是替换的是全部。
第三个replaceAll是替换全部的字符串正则表达式,
第四个是缺实是替换了第一个,但是人家名字写得明明白白的replaceFirst,而且替换的也是正则表达式。
教训与总结
这让我想起来前天的一篇文章《On The Value Of Fundamentals In Software Development 》,英文不好的可以自己翻译下。
我要好好学习Java的API了,白干了四年了,纯属一级菜鸟啊。
最新文章
- GitHub团队项目合作流程
- HTTP 协议的头部
- vector用法总结(转载)
- 【Cocos2d-x】源代码分析之 2d/ui/Widget
- [HMLY]9.深入浅出-iOS Reactive Cocoa的常见用法
- 【Python】三个例子教你写代码
- 不可思议的纯CSS导航栏下划线跟随效果
- linux搭建node环境超详细教程
- 数据cube的schema与sql的对应的关系
- SpringBoot整合Kafka和Storm
- ASP.NET结合Redis实现分布式缓存
- LeetCode练习3 找出一个字符串中最大不重复子字符串的长度
- 深入理解jQuery中的each方法
- python3.5环境配置
- 初始Redis
- TFS命令行操作
- js 判断是否是空对象
- 7 款顶级的开源 Web 分析软件
- phpstorm2018.3的安装和激活和汉化
- css points
热门文章
- phpredis报错信息:protocol error, got 'o' as reply type byte解决方案
- 小程序setdata json数据的方法
- SSH服务搭建、账号密码登录远程Linux虚拟机、基于密钥的安全验证(Windows_Xshell,Linux)
- python基础--选择排序
- cookie,seesion学习
- 通过yum在CentOS7部署LNMP环境(Centos7.4+Nginx1.12+mariadb5.5.56+PHP7.0)
- 【学习总结】Python-3-算术运算符中的/和//
- 批量授一种权限给用户程序 plm enovia
- JS事件委托(事件代理,dom2级事件)
- 用户Bug修补报告