比较Java中的Unicode字符(例如希腊语Delta)

时间:2015-06-30 08:15:16

标签: java string unicode char

我必须检查字符串的第一个字符是否是希腊三角洲。一项简单的任务。或不? 我很惊讶以下代码不起作用:

char first = myString.charAt(0);
boolean isDelta = first =='Δ';

如何解决我的问题?我找到的唯一方法是比较十六进制字符串:

 String unicodeForDelta = "394";
...
...
 char first = myString.charAt(0);
 boolean isDelta = unicodeForDelta.equals(Integer.toHexString(first));

这样可以或有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

它有效:

public class Delta {

    public static void main(String[] args) {
        String delta = "Δ";
        String str = "this string contains a Δ in it";

        char deltaChar = delta.charAt(0);

        System.out.println("str contains Δ: " + str.contains(delta));

        System.out.println((int) deltaChar);
        System.out.println((int) 'Δ');

        boolean isDelta = (deltaChar == 'Δ');

        System.out.println("is delta: " + isDelta);

        System.out.println("Integer.toHexString(deltaChar) = " + Integer.toHexString(deltaChar));

        System.out.println("Integer.toHexString(deltaChar) = " + Integer.toHexString(deltaChar));

        System.out.println( "\\u" + Integer.toHexString(deltaChar | 0x10000).substring(1) );

        String hexVal = "394";
        System.out.println("hexVal.equals(Integer.toHexString(deltaChar)) = " + hexVal.equals(Integer.toHexString(deltaChar)));
        System.out.println("hexVal == Integer.toHexString(deltaChar) = " + (hexVal == Integer.toHexString(deltaChar)));
    }
}

打印:

str contains Δ: true
916
916
is delta: true
Integer.toHexString(deltaChar) = 394
Integer.toHexString(deltaChar) = 394
\u0394
hexVal.equals(Integer.toHexString(deltaChar)) = true
hexVal == Integer.toHexString(deltaChar) = false

确保您的来源保存为UTF。 请注意,String ==检查它是否是相同的引用:它是内存中完全相同的对象

要比较对象的内容,您应该使用equals