Pau*_*ers 107 java string unicode character
我想在Java中显示Unicode字符.如果我这样做,它的工作正常:
String symbol = "\u2202";
符号等于"∂".这就是我想要的.
问题是我知道Unicode编号,需要从中创建Unicode符号.我试过(对我而言)显而易见的事情:
int c = 2202;
String symbol = "\\u" + c;
Run Code Online (Sandbox Code Playgroud)
但是,在这种情况下,符号等于"\ u2202".那不是我想要的.
如果我知道它的Unicode编号,我该如何构造符号(但仅在运行时---我不能像第一个例子那样硬编码)?
McD*_*ell 122
如果您想将UTF-16编码的代码单元作为a char,您可以解析整数并将其转换为其他人建议的.
如果要支持所有代码点,请使用Character.toChars(int).这将处理代码点不能适合单个char值的情况.
Doc说:
将指定字符(Unicode代码点)转换为存储在char数组中的UTF-16表示形式.如果指定的代码点是BMP(基本多语言平面或平面0)值,则生成的char数组与codePoint具有相同的值.如果指定的代码点是补充代码点,则生成的char数组具有相应的代理对.
dty*_*dty 67
只是把你int扔到一个char.您可以将其转换为String使用Character.toString():
String s = Character.toString((char)c);
Run Code Online (Sandbox Code Playgroud)
编辑:
请记住,Java源代码中的转义序列(\u位)是HEX,所以如果你试图重现转义序列,你需要类似的东西int c = 0x2202.
eis*_*eis 19
这里的其他答案要么只支持unicode到U + FFFF(只处理一个char实例的答案),要么不告诉如何获取实际符号(答案停在Character.toChars()或使用不正确的方法之后),所以在这里添加我的答案.
为了支持补充代码点,还需要做以下事情:
// this character:
// http://www.isthisthingon.org/unicode/index.php?page=1F&subpage=4&glyph=1F495
// using code points here, not U+n notation
// for equivalence with U+n, below would be 0xnnnn
int codePoint = 128149;
// converting to char[] pair
char[] charPair = Character.toChars(codePoint);
// and to String, containing the character we want
String symbol = new String(charPair);
// we now have str with the desired character as the first item
// confirm that we indeed have character with code point 128149
System.out.println("First code point: " + symbol.codePointAt(0));
Run Code Online (Sandbox Code Playgroud)
我还快速测试了哪些转换方法有效,哪些无效
int codePoint = 128149;
char[] charPair = Character.toChars(codePoint);
String str = new String(charPair, 0, 2);
System.out.println("First code point: " + str.codePointAt(0)); // 128149, worked
String str2 = charPair.toString();
System.out.println("Second code point: " + str2.codePointAt(0)); // 91, didn't work
String str3 = new String(charPair);
System.out.println("Third code point: " + str3.codePointAt(0)); // 128149, worked
String str4 = String.valueOf(code);
System.out.println("Fourth code point: " + str4.codePointAt(0)); // 49, didn't work
String str5 = new String(new int[] {codePoint}, 0, 1);
System.out.println("Fifth code point: " + str5.codePointAt(0)); // 128149, worked
Run Code Online (Sandbox Code Playgroud)
请记住,这char是一个整数类型,因此可以给出一个整数值,以及一个char常量.
char c = 0x2202;//aka 8706 in decimal. \u codepoints are in hex.
String s = String.valueOf(c);
Run Code Online (Sandbox Code Playgroud)
小智 6
这个对我很好.
String cc2 = "2202";
String text2 = String.valueOf(Character.toChars(Integer.parseInt(cc2, 16)));
Run Code Online (Sandbox Code Playgroud)
现在text2将有∂.
小智 6
String st="2202";
int cp=Integer.parseInt(st,16);// it convert st into hex number.
char c[]=Character.toChars(cp);
System.out.println(c);// its display the character corresponding to '\u2202'.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
235650 次 |
| 最近记录: |