其实标题应改为过滤4字节UTF-8字符
请看下表
Unicode编码(16进制) ║ UTF-8 字节流(二进制)
000000 - 00007F ║ 0xxxxxxx
000080 - 0007FF ║ 110xxxxx 10xxxxxx
000800 - 00FFFF ║ 1110xxxx 10xxxxxx 10xxxxxx
010000 - 10FFFF ║ 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
作者给出了两套算法:
public static String filterOffUtf8Mb4_2(String text) throws UnsupportedEncodingException {
byte[] bytes = text.getBytes("utf-8");
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
int i = 0;
while (i < bytes.length) {
short b = bytes[i];
if (b > 0) {
buffer.put(bytes[i++]);
continue;
}
b += 256; //去掉符号位
if (((b >> 5) ^ 0x06) == 0) {
buffer.put(bytes, i, 2);
i += 2;
System.out.println("2");
} else if (((b >> 4) ^ 0x0E) == 0) {
System.out.println("3");
buffer.put(bytes, i, 3);
i += 3;
} else if (((b >> 3) ^ 0x1E) == 0) {
i += 4;
System.out.println("4");
} else if (((b >> 2) ^ 0xBE) == 0) {
i += 5;
System.out.println("5");
} else {
i += 6;
System.out.println("6");
}
}
buffer.flip();
return new String(buffer.array(), "utf-8");
}
static public String filterOffUtf8Mb4(String text) throws UnsupportedEncodingException {
byte[] bytes = text.getBytes("utf-8");
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
int i = 0;
while (i < bytes.length) {
short b = bytes[i];
if (b > 0) {
buffer.put(bytes[i++]);
continue;
}
b += 256;
if ((b ^ 0xC0) >> 4 == 0) {
buffer.put(bytes, i, 2);
i += 2;
}
else if ((b ^ 0xE0) >> 4 == 0) {
buffer.put(bytes, i, 3);
i += 3;
}
else if ((b ^ 0xF0) >> 4 == 0) {
i += 4;
}
}
buffer.flip();
return new String(buffer.array(), "utf-8");
}
经过测试第二段代码是错的,因为它固定右移4位导致遇到ф等字符时出现了死循环。因为大家代码都是抄来抄去,请大家一定注意用第一段代码