Java:如何从字符串创建unicode\u00C3“;等
我有一个手动键入字符串为\u00C3的文件。我想创建一个unicode字符,它由java中的unicode表示。我试过了,但找不到方法。救命啊Java:如何从字符串创建unicode\u00C3“;等,java,unicode,unicode-string,Java,Unicode,Unicode String,我有一个手动键入字符串为\u00C3的文件。我想创建一个unicode字符,它由java中的unicode表示。我试过了,但找不到方法。救命啊 编辑:当我读取文本文件时,字符串将包含“\u00C3”而不是unicode字符,而是ASCII字符“\''u''0''0''3”。我想从ASCII字符串中生成unicode字符。我在web上的某个地方找到了这个: String unescape(String s) { int i=0, len=s.length(); char c;
编辑:当我读取文本文件时,字符串将包含“\u00C3”而不是unicode字符,而是ASCII字符“\''u''0''0''3”。我想从ASCII字符串中生成unicode字符。我在web上的某个地方找到了这个:
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();
}
stringunescape(字符串s){
int i=0,len=s.length();
字符c;
StringBuffer sb=新的StringBuffer(len);
而(我
大概是这样的:
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
)
)
);
该死,我有点慢。以下是我的解决方案:
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));
}
}
}
}
StringEscapeUtils.unescapeJava工作正常:)
请参阅:如果希望仅转义unicode而不转义其他内容,可以通过编程方式创建函数:
private String unicodeUnescape(String string) {
return new UnicodeUnescaper().translate(string);
}
这使用org.apache.commons.text.translate.Unicoduenscaper。文件的格式如何?这些字符串是一行还是什么?是的,每一行都有自己的字符串(对不起,我不能复制换行符)\u0103\u0104\u0105\u01cd工作得很好-谢谢你,我已经挣扎了4个小时了。如果我可以告诉你,你在谷歌上搜索了什么来找到解决方案:)我记得,它有点像
javaunescape string