Java中以字节长度截取存在中文的字符串(UTF-8编码)


背景:以定长字节输出含中文字符时,因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你

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM