以定长字节输出含中文字符时,因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));
}```
该博客探讨了在处理包含中文字符的字符串时,由于ASCII、GBK和UTF-8编码字节长度不同可能导致的截取长度超出问题。提供了两种方法(方法1和方法2)来确保在UTF-8编码下,字符串截取不超过指定长度。方法通过循环减少截取长度,直到转换为UTF-8编码后的字节数不超过目标长度。

2296

被折叠的 条评论
为什么被折叠?



