Java:如何从字符串“\ u00C3”等创建unicode

我有一个文件,其字符串手写为\ u00C3。 我想创建一个由java中的unicode表示的unicode字符。 我试过但找不到怎么样。 帮帮我。

编辑:当我读取文本文件时,字符串将包含“\ u00C3”而不是unicode但是包含ASCII字符’\”u”0”0”3’。 我想从该ASCII字符串中形成unicode字符。

我在网上的某个地方选了这个:

String unescape(String s) { int i=0, len=s.length(); char c; StringBuffer sb = new StringBuffer(len); while (i < len) { c = s.charAt(i++); if (c == '\\') { if (i < len) { c = s.charAt(i++); if (c == 'u') { // TODO: check that 4 more chars exist and are all hex digits c = (char) Integer.parseInt(s.substring(i, i+4), 16); i += 4; } // add other cases here as desired... } } // fall through: \ escapes itself, quotes any character but u sb.append(c); } return sb.toString(); } 

Dang,我有点慢。 这是我的解决方案:

 package ravi; import java.io.BufferedReader; import java.io.FileReader; import java.util.regex.Pattern; public class Ravi { private static final Pattern UCODE_PATTERN = Pattern.compile("\\\\u[0-9a-fA-F]{4}"); public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader("ravi.txt")); while (true) { String line = br.readLine(); if (line == null) break; if (!UCODE_PATTERN.matcher(line).matches()) { System.err.println("Bad input: " + line); } else { String hex = line.substring(2,6); int number = Integer.parseInt(hex, 16); System.out.println(hex + " -> " + ((char) number)); } } } } 

可能有些事情:

 Scanner s = new Scanner( new File("myNumbers") ); while( s.hasNextLine() ) { System.out.println( Character.valueOf( (char)(int) Integer.valueOf( s.nextLine().substring(2,6), 16 ) ) ); 

StringEscapeUtils.unescapeJava工作正常:)

请参阅: https : //commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#unescapeJava(java.lang.String)

如果你只想以编程方式转义unicode而不是其他任何东西,你可以创建一个函数:

 private String unicodeUnescape(String string) { return new UnicodeUnescaper().translate(string); } 

这使用org.apache.commons.text.translate.UnicodeUnescaper。