背景:以定長字節輸出含中文字符時,因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你