private static final byte UTF8_HIGH_MASK = (byte)0xf0;
public static Boolean has4BytesUTF8(String str){
if(StringUtils.isBlank(str)){
return false;
}
try {
byte[] bytes = str.getBytes("UTF8");
for(byte b : bytes){
if(((byte)(b&UTF8_HIGH_MASK))==UTF8_HIGH_MASK){
return true;
}
}
return false;
} catch (UnsupportedEncodingException e) {
return false;
}
}
代码上有可优化之处,比如不必遍历所有字节,可以根据字节高位的pattern,一次跳过多个字节。
本文来自网易实践者社区,经作者程义授权发布。