以定长字节输出含中文字符时,因ASCII码字符占1字节,而中文GBK字符占2字节,中文UTF-8字符占3字节,为避免输出长度超过定长,故需对含中文的内容进行处理。
// 方法1
public static String subStrUtf8(String str, int beginIndex, int endIndex) {
String subStr = "";
try {
int byteEndIndex = Math.min(str.length(), endIndex);
int byteLen = 0;
do {
// 将要截取的子串长度减1,此处切记用 byteEndIndex--,而不是 --byteEndIndex
subStr = str.substring(beginIndex, byteEndIndex--);
// 更新subStr转为UTF-8的byte[]的长度
byteLen = subStr.getBytes("UTF-8").length;
// 只要byteLen大于最初想要截取的子串的值,则继续循环
} while (byteLen > endIndex - beginIndex);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return subStr;
}
//方法2
public static String subStrUtf8(String str, int subLen) {
String subStr = "";
try {
int byteEndIndex = Math.min(str.length(), subLen);
int byteLen = 0;
do {
// 将要截取的子串长度减1,此处切记用 byteEndIndex--,而不是 --byteEndIndex
subStr = str.substring(0, byteEndIndex--);
// 更新subStr转为UTF-8的byte[]的长度
byteLen = subStr.getBytes("UTF-8").length;
// 只要byteLen大于最初想要截取的子串的值,则继续循环
} while (byteLen > subLen);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return subStr;
}
public static void main(String[] args) {
String str = "abcd你好efgh谢谢";
System.out.println(subStrUtf8(str, 0, 8));
System.out.println(subStrUtf8(str, 8));
}```