1、字符與字節
拋出如下代碼:
public static void main(String[] args) { String str = "活出自己范兒"; System.out.println(str.length()); System.out.println(str.getBytes("GBK").length); }
執行結果:
6
12
結論:
String.length():返回字符串的字符個數,一個中文算一個字符;
String.getBytes().length:返回字符串的字節長度,一個中文兩個字節;
2、字節長度
拋出一段代碼:
public static void main(String[] args) { String str = "活出自己范"; System.out.println(str.length()); try { System.out.println(str.getBytes().length); System.out.println("GBK=="+str.getBytes("GBK").length); System.out.println("UTF-8=="+str.getBytes("UTF-8").length); System.out.println("GB2312=="+str.getBytes("GB2312").length); System.out.println("ISO-8859-1=="+str.getBytes("ISO-8859-1").length); } catch (Exception e) { e.printStackTrace(); } }
執行結果:
6 18 GBK==12 UTF-8==18 GB2312==12 ISO-8859-1==6
結論:
String.getBytes().length方法是得到一個字串的字節數組的長度,在獲得字符串的字節數組的長度的時候,需要制定編碼格式,否則會默認操作系統的編碼格式:
此博文來源於:https://www.jianshu.com/p/b939412d8c38