Java String.toLowerCase() & String.toUpperCase() 区域敏感

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

toLowerCase & toUpperCase


以下文档来自 Java 8 API

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的方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,010评论 19 139
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,780评论 18 399
  • 她总是有声音的 在我清醒的时候午睡的时候 平静的时候焦躁的时候 她把手机摔在桌子上 把杯子扔到窗台上 把鞋踢到椅子...
    草垛阅读 901评论 11 7
  • 这篇文章介绍一个东西,我管它叫代理拦截器,顾名思义就是拦截代理事件的一个东西。还有一个代理分发器。两者的使用场景和...
    youlianchun阅读 722评论 0 0