Java:将字符串“\ uFFFF”转换为char
是否有一种标准方法将像“\ uFFFF”这样的字符串转换为字符,这意味着六个字符的字符串包含一个unicode字符的表示?
char c = "\uFFFF".toCharArray()[0];
该值直接解释为所需的字符串,整个序列实现为单个字符。
另一种方法,如果您要对值进行硬编码:
char c = '\uFFFF';
请注意, \uFFFF
似乎不是一个正确的unicode字符,但请尝试使用\u041f
。
阅读有关unicode逃逸的信息
反斜杠在这里被转义(所以你看到其中两个,但s String实际上只有6个字符长)。 如果您确定在字符串的开头有“\ u”,只需跳过它们并转换hex值:
String s = "\\u20ac"; char c = (char) Integer.parseInt( s.substring(2), 16 );
之后, c应按预期包含欧元符号。
如果使用Java样式转义字符解析输入,则可能需要查看StringEscapeUtils.unescapeJava 。 它处理Unicode转义以及换行符,制表符等。
String s = StringEscapeUtils.unescapeJava("\\u20ac\\n"); // s contains the euro symbol followed by newline
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'