背景:以定长字节输出含中文字符时,因ASCII码字符占1字节,而中文GBK字符占2字节,中文UTF-8字符占3字节,为避免输出长度超过定长,故需对含中文的内容进行处理。
此处以输出UTF-8为例,其他编码同理。
1 // 方法1 2 public static String subStrUtf8(String str, int beginIndex, int endIndex) { 3 String subStr = ""; 4 try { 5 int byteEndIndex = Math.min(str.length(), endIndex); 6 int byteLen = 0; 7 do { 8 // 将要截取的子串长度减1,此处切记用 byteEndIndex--,而不是 --byteEndIndex 9 subStr = str.substring(beginIndex, byteEndIndex--); 10 11 // 更新subStr转为UTF-8的byte[]的长度 12 byteLen = subStr.getBytes("UTF-8").length; 13 14 // 只要byteLen大于最初想要截取的子串的值,则继续循环 15 } while (byteLen > endIndex - beginIndex); 16 } catch (UnsupportedEncodingException e) { 17 e.printStackTrace(); 18 } 19 return subStr; 20 } 21 22 //方法2 23 public static String subStrUtf8(String str, int subLen) { 24 String subStr = ""; 25 try { 26 int byteEndIndex = Math.min(str.length(), subLen); 27 int byteLen = 0; 28 do { 29 // 将要截取的子串长度减1,此处切记用 byteEndIndex--,而不是 --byteEndIndex 30 subStr = str.substring(0, byteEndIndex--); 31 32 // 更新subStr转为UTF-8的byte[]的长度 33 byteLen = subStr.getBytes("UTF-8").length; 34 35 // 只要byteLen大于最初想要截取的子串的值,则继续循环 36 } while (byteLen > subLen); 37 } catch (UnsupportedEncodingException e) { 38 e.printStackTrace(); 39 } 40 return subStr; 41 } 42 43 public static void main(String[] args) { 44 String str = "abcd你好efgh谢谢"; 45 System.out.println(subStrUtf8(str, 0, 8)); 46 System.out.println(subStrUtf8(str, 8)); 47 }
运行结果:
abcd你
abcd你