7

我有一个文件,其中包含手动键入为 \u00C3 的字符串。我想在java中创建一个由该unicode表示的unicode字符。我试过但找不到方法。帮助。

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

4

5 回答 5

7

我在网上某处捡到这个:

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();
}
于 2011-02-14T21:22:34.737 回答
3

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

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));
            }
        }
    }

}
于 2011-02-14T21:35:26.217 回答
0

大概是这样的:

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
            )
        )
   );
于 2011-02-14T21:33:15.283 回答
0

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

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

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

于 2018-01-19T08:11:55.170 回答
0

StringEscapeUtils.unescapeJava 工作正常:)

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

于 2017-08-12T05:30:41.270 回答