【发布时间】:2017-11-07 00:46:08
【问题描述】:
我有一个函数“remove4BytesUTF8Char()”来删除社交媒体中出现的一些独特字符,但它不起作用。我可以删除很多其他字符,但不能删除这个。如何从我的字符串中专门摆脱这个?
String str = "very good\uE056 flavor";
System.out.println("str before remove: " + str);
str = UTF8Utils.remove4BytesUTF8Char(str);
System.out.println("str after remove " + str);
输出如下:
str before remove: very good flavor
str after remove very good flavor
编辑:
public static String remove4BytesUTF8Char(String s) {
byte[] bytes = s.getBytes();
byte[] removedBytes = new byte[bytes.length];
int index = 0;
String hex;
String firstChar;
for (int i = 0; i < bytes.length; ) {
hex = UTF8Utils.byteToHex(bytes[i]);
if (hex.length() < 2) {
System.out.println("fail to check whether contains 4 bytes char(1 byte hex char too short), default return false.");
// todo, throw exception for this case
return null;
}
firstChar = hex.substring(0, 1);
if (byteMap.get(firstChar) == null) {
System.out.println("fail to check whether contains 4 bytes char(no firstchar mapping), default return false.");
// todo, throw exception for this case
return null;
}
if (firstChar.equals("f")) {
for (int j = 0; j < byteMap.get(firstChar); j++) {
i++;
}
continue;
}
for (int j = 0; j < byteMap.get(firstChar); j++) {
removedBytes[index++] = bytes[i++];
}
}
return new String(Arrays.copyOfRange(removedBytes, 0, index));
}
【问题讨论】:
-
你已经看过this了吗?
-
你还没有发布你的函数 remove4BytesUTF8Char。如果没有有问题的代码,我们将无能为力。
-
“嗨,机械师乔。我的车坏了,所以我把它留在家里,然后骑着自行车来这里。请你看看我的自行车,告诉我我的车出了什么问题吗? "
-
@ErwinBolwidt,我添加了我正在使用的功能。
-
注意:
s.getBytes()在 Windows 上不会返回 UTF-8 字节。