2017-04-05 4 views
1

Javaで単一のUnicode文字を表現したいと考えています。これに適したプリミティブまたはクラスはどれですか?Javaで単一のUnicode文字を表現する方法はありますか?

2バイトの場合には大きすぎるユニコード文字を保存できるようにしたいことに注意してください。char

+1

'char'を使うことができます – prasanth

+0

' char ch = '\ u1111'; ' –

+2

@prasanth:' char'はすべてのUnicode文字を保持できません。 'char'は基本的にUTF-16コードユニットに対応します。 –

答えて

9

charは、実際には16ビットのa char corresponds to a UTF-16 code unitです。 1つのUTF-16コードユニット(Emojisなど)に収まらない文字には、2つのcharが必要です。

何らかの理由で個別に保管する必要がある場合は、intを使用できます。現在Unicodeで許可されているすべての0x10FFFFコードポイントに十分な余裕があります(そしていくつか)。これは、JDKが使用するものです。例えば、Character.codePointAt(CharSequence seq, int index)String(int[] codePoints, int offset, int count)です。

無償変換例(live on ideone):

String s = ""; 
int emoji = Character.codePointAt(s, 0); 
String unumber = "U+" + Integer.toHexString(emoji).toUpperCase(); 
System.out.println(s + " is code point " + unumber); 
String s2 = new String(new int[] { emoji }, 0, 1); 
System.out.println("Code point " + unumber + " converted back to string: " + s2); 
System.out.println("Successful round-trip? " + s.equals(s2)); 

出力:

 
    is code point U+1F602 
Code point U+1F602 converted back to string: 
Successful round-trip? true 
1

は、文字の定義に依存:あなたが1つのUnicodeコードポイントを意味している場合

intを使用します。これは、U + 0000からU + 1FFFFFまでのすべての値を保持できます。

しかし、場合によっては、1文字として表示されるものが複数のコードポイントを占有します。これは、特に絵文字でよく使用されます(例:emoji)。

これらを最も論理的に保存するには、Stringを使用してください。

+0

**#EmojiCodeSheet ** [here](https://github.com/shanraisshan/EmojiCodeSheet)で、すべての絵文字のリストをstring/int形式で見つけることができます。 – shanraisshan

関連する問題