閒話少說直接上代碼
public static boolean isContainSpecialChar(String str) {
if(StringUtils.isEmpty(str)){
return false;
}
try {
byte[] bytes = str.getBytes("UTF-8");
for (int i = 0; i < bytes.length; i++) {
if(isStartWithOver3Byte(bytes[i])){
return true;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return false;
}
/**
* 判斷字節範圍是否在四,五,六範圍內
*
* 1字節 0xxxxxxx
* 2字節 110xxxxx 10xxxxxx
* 3字節 1110xxxx 10xxxxxx 10xxxxxx
* 4字節 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
* 5字節 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
* 6字節 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
* @param b
* @return
*/
public static boolean isStartWithOver3Byte(byte b) {
int unsignByte = Byte.toUnsignedInt(b);
return (0xf0 <= unsignByte && unsignByte <= 0xf7) ||//4字節開頭
(0xf8 <= unsignByte && unsignByte <= 0xfb) ||//5字節開頭
(0xfc <= unsignByte && unsignByte <= 0xfd);//6字節開頭
}
public static void main(String[] args){
String str="€😘jekj,fj€dks@";//笑臉4個字節
String str2="⏰kjsfjfjfj";//鬧鐘三個字節
String str3="€";//三個字節
System.out.println(isContainSpecialChar(str));
System.out.println(isContainSpecialChar(str2));
System.out.println(isContainSpecialChar(str3));
}