java string case_Java String.toLowerCase() & String.toUpperCase() 区域敏感

我现在比较喜欢看API相关文档了,总会有些特别的收获的。比如这一次我发现,原来String的某些方法,我一直都理解错了。

toLowerCase & toUpperCase

public String toLowerCase()

Converts all of the characters in this String to lower case using the rules of the default locale. This is equivalent to calling toLowerCase(Locale.getDefault()).

Note: This method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently. Examples are programming language identifiers, protocol keys, and HTML tags. For instance, "TITLE".toLowerCase() in a Turkish locale returns "t\u0131tle", where '\u0131' is the LATIN SMALL LETTER DOTLESS I character. To obtain correct results for locale insensitive strings, use toLowerCase(Locale.ROOT).

Returns:

the String, converted to lowercase.

See Also:

toLowerCase(Locale)

public String toUpperCase()

Converts all of the characters in this String to upper case using the rules of the default locale. This method is equivalent to toUpperCase(Locale.getDefault()).

Note: This method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently. Examples are programming language identifiers, protocol keys, and HTML tags. For instance, "title".toUpperCase() in a Turkish locale returns "T\u0130TLE", where '\u0130' is the LATIN CAPITAL LETTER I WITH DOT ABOVE character. To obtain correct results for locale insensitive strings, use toUpperCase(Locale.ROOT).

Returns:

the String, converted to uppercase.

See Also:

toUpperCase(Locale)

如上所言,“LITTLE”.toLowerCase()在不同的语言环境下返回的结果是不同的,也就是说,toLowerCase()方法(注意,这里是无参数的方法)是区域敏感的。而如果想得到统一的结果的话,可以调用toLowerCase(Locale.ROOT) (Java 8的建议)或toLowerCase(Locale.ENGLISH) (Java 7以前的建议)。toUpperCase同理。

如果在业务逻辑中大小写敏感的话,极不推荐toLowerCase()方法,因为无法确保软件是否会跨区域使用,万一有跨区域使用情形,将会带来难以排查的bug。

思考:

如果大小写转化只是用于显示的话,建议用默认的无参数方法即可。而如果大小写转化用于业务逻辑的话,强烈建议采用指定Locale.ROOT或Locale.ENGLISH的方法。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值