在Java中是否有办法获取任何字符的Unicode等效值?例如:
假设有一个方法getUnicode(char c)
。调用getUnicode('÷')
应该返回\u00f7
。
你可以使用这个一行代码来处理任何Java字符:
System.out.println( "\\u" + Integer.toHexString('÷' | 0x10000).substring(1) );
但它只能处理Unicode字符直到Unicode 3.0,这就是为什么我强调你可以用任何Java字符来完成它。
由于Java在Unicode 3.1出现之前就被设计了,所以Java的char原始类型不足以表示Unicode 3.1及以上版本:不再有“一个Unicode字符对应一个Java char”的映射(而是使用了一个巨大的hack)。
因此,在这里您确实需要检查您的要求:您是否需要支持Java char或任何可能的Unicode字符?
String.charAt
返回“半个字符”,而String.length
返回的内容可能与字符数不同,这不是很丑陋吗?(这里的“字符”指Unicode代码点,而不是Java字符)String类应该是独立于编码问题的(在Unicode 3.1之前也确实如此)。 - Thilo如果您使用Java 5,请使用char c = ...; String s = String.format ("\\u%04x", (int)c);
如果您的源不是Unicode字符(char
)而是字符串,则必须使用charAt(index)
获取位置index
处的Unicode字符。
不要使用codePointAt(index)
,因为它将返回24位值(完整的Unicode),这些值无法仅用4个十六进制数字(需要6个)表示。请参见文档以获得说明。
[编辑]为了清楚起见:此答案不是使用Unicode,而是Java用于表示Unicode字符的方法(即代理对),因为char
是16位,而Unicode是24位。问题应该是:“如何将char
转换为4位十六进制数”,因为它并不(真正地)与Unicode有关。
private static String toUnicode(char ch) {
return String.format("\\u%04x", (int) ch);
}
( "\\u" + Integer.toHexString('÷' | 0x10000).substring(1) )
到底是什么鬼? - Все Едноchar c = 'a';
String a = Integer.toHexString(c); // gives you---> a = "61"
我在网上找到了这段不错的代码。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Unicode {
public static void main(String[] args) {
System.out.println("Use CTRL+C to quite to program.");
// Create the reader for reading in the text typed in the console.
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
try {
String line = null;
while ((line = bufferedReader.readLine()).length() > 0) {
for (int index = 0; index < line.length(); index++) {
// Convert the integer to a hexadecimal code.
String hexCode = Integer.toHexString(line.codePointAt(index)).toUpperCase();
// but the it must be a four number value.
String hexCodeWithAllLeadingZeros = "0000" + hexCode;
String hexCodeWithLeadingZeros = hexCodeWithAllLeadingZeros.substring(hexCodeWithAllLeadingZeros.length()-4);
System.out.println("\\u" + hexCodeWithLeadingZeros);
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
你是否对使用Unicode很挑剔?因为如果你编写程序使用“dec”值或(HTML-Code),那么你可以在char和int之间简单地进行数据类型转换,这在Java中更加简单。
char a = 98;
char b = 'b';
char c = (char) (b+0002);
System.out.println(a);
System.out.println((int)b);
System.out.println((int)c);
System.out.println(c);
输出以下内容
b
98
100
d