Portability Flaw Locale Dependent Comparison

Portability Flaw Locale Dependent Comparison

【问题描述】

该问题涉及String的toUpperCase()方法。具体通过例子演示相关现象。

 

public class TestString

{

    public static void main(String[] args)

    {

        String str = "Title";

        System.out.println(str.toUpperCase());

    }

}

我们期望的结果为TITLE。

在正常逻辑下这个是没有问题的,但是当本地语言是土耳其语言时,就会发生问题。

 

import java.util.Locale;

 

public class TestString

{

    public static void main(String[] args)

    {

        Locale.setDefault(Locale.forLanguageTag("tr"));

        String str = "Title";

        System.out.println(str.toUpperCase());

    }

}

输出结果就变成了这个:

T?TLE

实际上这个?表示的是大写的I,在土耳其语系中,其I的表示方式为İ。

【解决方案】

import java.util.Locale;

 

public class TestString

{

    public static void main(String[] args)

    {

        Locale.setDefault(Locale.forLanguageTag("tr"));

        String str = "Title";

        System.out.println(str.toUpperCase(Locale.ENGLISH));//这里是重点,用设置使用语言进行转换,避免结果与预期不一致

    }

}

 

 

参考链接:https://wiki.sei.cmu.edu/confluence/display/java/Rule+AA.+References#RuleAA.References-API06

原文地址:https://www.cnblogs.com/woniu4/p/9233638.html