Java:将字符串“\uFFFF”转换为字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2126378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:49:45  来源:igfitidea点击:

Java: Convert String "\uFFFF" into char

javaunicode

提问by Dima

Is there a standard method to convert a string like "\uFFFF" into character meaning that the string of six character contains a presentation of one unicode character?

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

采纳答案by Bozho

char c = "\uFFFF".toCharArray()[0];

The value is directly interpreted as the desired string, and the whole sequence is realized as a single character.

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

Another way, if you are going to hard-code the value:

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

char c = '\uFFFF';

Note that \uFFFFdoesn't seem to be a proper unicode character, but try with \u041ffor example.

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

Read about unicode escapes here

在此处阅读有关 unicode 转义的信息

回答by SyntaxT3rr0r

The backslash is escaped here (so you see two of them but the sString is really only 6 characters long). If you're surethat you have exactly "\u" at the beginning of your string, simply skip them and converter the hexadecimal value:

反斜杠在此处转义(因此您可以看到其中两个,但s字符串实际上只有 6 个字符长)。如果您确定字符串的开头正好有“\u”,只需跳过它们并转换十六进制值:

String s = "\u20ac";

char c = (char) Integer.parseInt( s.substring(2), 16 );

After that cshall contain the euro symbol as expected.

之后c应包含预期的欧元符号。

回答by Yoni

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'

回答by stoivane

If you are parsing input with Java style escaped characters you might want to have a look at StringEscapeUtils.unescapeJava. It handles Unicode escapes as well as newlines, tabs etc.

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

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