2011-02-14 111 views
7

我有一个文件,其中键入的字符串为\ u00C3。我想创建一个由java中的unicode代表的unicode字符。我试过但找不到。帮帮我。Java:如何从字符串“ u00C3”创建unicode等

编辑:当我读取文本文件字符串将包含“\ u00C3”不作为unicode,但作为ASCII字符'\''''0''0''3'。我想从那个ASCII字符串中形成unicode字符。

+0

文件格式如何?这些字符串是一对一的,还是什么? – 2011-02-14 21:15:21

+0

是的,每个人在自己的线路(抱歉,我不能重现换行符贝雷) \ u0103 \ u0104 \ u0105 \ u01CD – Ravi 2011-02-14 21:16:36

回答

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

} 
0

如果你想逃避只有统一,没有别的,编程,你可以创建一个函数:

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

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