Java:将字符串"\ uFFFF"转换为char

Dim*_*ima 29 java unicode

是否有一种标准方法将像"\ uFFFF"这样的字符串转换为字符,这意味着六个字符的字符串包含一个unicode字符的表示形式?

Boz*_*zho 34

char c = "\uFFFF".toCharArray()[0];
Run Code Online (Sandbox Code Playgroud)

该值直接解释为所需的字符串,整个序列实现为单个字符.

另一种方法,如果您要对值进行硬编码:

char c = '\uFFFF';
Run Code Online (Sandbox Code Playgroud)

请注意,这\uFFFF似乎不是一个正确的unicode字符,但请尝试使用\u041f例如.

在这里阅读有关unicode逃逸的信息


Syn*_*r0r 19

反斜杠在这里被转义(所以你看到其中两个,但s String实际上只有6个字符长).如果您确定在字符串的开头只有"\ u",只需跳过它们并转换十六进制值:

String s = "\\u20ac";

char c = (char) Integer.parseInt( s.substring(2), 16 );
Run Code Online (Sandbox Code Playgroud)

之后,c应按预期包含欧元符号.


小智 18

如果要使用Java样式转义字符解析输入,可能需要查看StringEscapeUtils.unescapeJava.它处理Unicode转义以及换行符,制表符等.

String s = StringEscapeUtils.unescapeJava("\\u20ac\\n"); // s contains the euro symbol followed by newline
Run Code Online (Sandbox Code Playgroud)


Yon*_*oni 6

String charInUnicode = "\\u0041"; // ascii code 65, the letter 'A'
Integer code = Integer.parseInt(charInUnicode.substring(2), 16); // the integer 65 in base 10
char ch = Character.toChars(code)[0]; // the letter 'A'
Run Code Online (Sandbox Code Playgroud)