我需要使用转义字符“\”及其十六进制值替换字符串中的所有特殊unicode字符。 例如,这个字符串:
String test="This is a string with the special è unicode char";
将Shuld替换为:
"This is a string with the special \E8 unicode char";
其中E8是char“è”的unicode值的十六进制值。
答案 0 :(得分:0)
我有两个问题:
1)如何找到“特殊字符”,如果是> 127,我可以检查每个字符值吗?
这取决于你对“特殊”字符的定义。测试大于127的字符是测试非ASCII字符。由你决定这是否是你想要的。
2)以及如何将十六进制值作为字符串。
可以使用Integer.toHexString
方法。
3)我可以使用正则表达式为字符串的每个字符找到它或循环吗?
循环更简单。
答案 1 :(得分:0)
我正在尝试使用正则表达式替换此解决方案(我不知道为字符串中的每个字符串循环或使用正则表达式是否更好...)
String test="This is a string with the special è unicode char";
Pattern pat=Pattern.compile("([^\\x20-\\x7E])");
int offset=0;
Matcher m=pat.matcher(test);
while(!m.hitEnd()) {
if (m.find(offset)) {
out.append(test.substring(offset,m.start()));
for(int i=0;i<m.group(1).length();i++){
out.append(ESCAPE_CHAR);
out.append(Integer.toHexString(m.group(1).charAt(i)).toUpperCase());
}
offset=m.end();
}
}
return out.toString();
答案 2 :(得分:0)
如果您的unicode字符都在\ u0080 - \ u00FF范围内,您可以使用此解决方案。
public class Convert {
public static void main(String[] args) {
String in = "This is a string with the special è unicode char";
StringBuilder out = new StringBuilder(in.length());
for (int i = 0; i < in.length(); i++) {
char charAt = in.charAt(i);
if (charAt > 127) {
// if there is a high number (several e.g. 100.000) of conversions
// this lead in less objects to be garbadge collected
out.append('\\').append(Integer.toHexString(charAt).toUpperCase());
// out.append(String.format("\\%X", (int) charAt));
} else {
out.append(charAt);
}
}
System.out.println(out);
}
}