jdk中String对象的replace和replaceAll方法

java作为目前最受开发者欢迎以及热度最高的一门语言,在很多方面展现出了其特性,虽然灵活性不比c++,执行效率不比c,开发效率不比Ruby,但是作为最早最纯粹的OO语言,java在目前来说因为其在编程方面有着与c及c++语言的延续性而被广泛的使用。
即使java是如此的受欢迎,个人觉得jdk的api在很多方面却做的不是太好,简单的以命名来说。比如说string类的两个方法replace和replaceAll,因为有replaceAll的存在根据命名来看很容易使人觉得第一个replace方法是用replacement字串替换source字串中第一个出现的 target字符串,而replaceAll方法是替换在source字串中所出现的所有 target字串。

至少在jdk中它们是这样声明的:
public String replaceAll(String regex, String replacement) {...}

public String replace(CharSequence target, CharSequence replacement){...}

如果不去阅读它们的注释或者查看具体实现,你自然的觉得它们二者就只是存在着替换数量之间的差别,一个是全部替换,另外一个只是替换第一个(至少我是这样理解的,并且在此api上面也吃过一些亏)。

二者的注释分别为:
replaceAll 
Replaces each substring of this string that matches the given regular expression with the given replacement.

replace
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".

到此才得知replaceAll是采用正则表达式进行文本的替换,替换所有满足条件的substring。
replace是采用文本本身的内容进行匹配替换,也是 所有满足条件的substring。

例如下面的代码:
                String info = "catfish+foolishcat";
		String withReplace = info.replace("catfish+", "rxr");
		String withReplaceAll = info.replaceAll("catfish+", "rxr");
		System.out.println("withReplace    is " + withReplace);
		System.out.println("withReplaceAll is " + withReplaceAll);
最后的输出分别为:
withReplace    is rxrfoolishcat
withReplaceAll is rxr+foolishcat

所以这两个方法在命名上面给开发者的歧义性太大,不具备可读性,至少不能望文生义,replace替换成replaceWithLiteralTarget,replaceAll替换成replaceWithRegexTarget能够从语义上面区分出二者的差别。

针对replace和replaceAll命名的就说这么多,有时间把个人认为jdk中不好的一些define都拿出来记录一下,以免以后犯同样的错误。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值