这里的需求是,如果截取长度刚好在中文字符或者表情上,则舍弃这个字符,因为中文和表情的字节长度不为1
public static String substringToByte(String str, int byteLength) {
StringBuilder result = new StringBuilder();
int count = 0;
String temp = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// 判断是否是emoji表情
if (Character.isHighSurrogate(c) && i + 1 < str.length()) {
char nextChar = str.charAt(i + 1);
if (Character.isLowSurrogate(nextChar)) {
temp = c + String.valueOf(nextChar);
count += temp.getBytes().length;
i++;
}
} else {
temp = Character.toString(c);
count += temp.getBytes().length;
}
if (count > byteLength) {
break;
}
result.append(temp);
}
return result.toString();
}