java 过滤非utf8_Java 过滤非汉字的utf8的字符(包括emoji)

这篇博客介绍了如何在Java中过滤掉非汉字的4字节UTF-8字符,包括emoji。作者提供了两段代码,但指出第二段存在错误,可能导致死循环。建议使用第一段代码进行正确过滤。
摘要由CSDN通过智能技术生成

其实标题应改为过滤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位导致遇到ф等字符时出现了死循环。因为大家代码都是抄来抄去,请大家一定注意用第一段代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值