參考:https://colobu.com/2019/01/04/how-many-charactors-in-a-java-string/
https://www.ibm.com/developerworks/cn/java/j-lo-chinesecoding/index.html
//獲取系統(tǒng)默認編碼
System.out.println("系統(tǒng)默認編碼:" + System.getProperty("file.encoding")); //查詢結(jié)果UTF-8
//系統(tǒng)默認字符編碼
System.out.println("系統(tǒng)默認字符編碼:" + Charset.defaultCharset()); //查詢結(jié)果UTF-8
//操作系統(tǒng)用戶使用的語言
System.out.println("系統(tǒng)默認語言:" + System.getProperty("user.language")); //查詢結(jié)果zh
System.out.println();
// String s1 = "hi,我來了";
String s1 = "a b c";
String urf16 = new String(s1.getBytes(), Charset.forName("UTF-16"));
System.out.println(urf16.length());
System.out.println(urf16.getBytes("UTF-16").length);
System.out.println(urf16.toCharArray().length);
for (char c : urf16.toCharArray()) {
System.out.println(c);
}
for (int c : urf16.toCharArray()) {
System.out.print(c + " ");
}
System.out.println("\n======defaultCharset=====");
String utf8 = new String(s1.getBytes(), Charset.forName("UTF-8"));
System.out.println(utf8.length());
System.out.println(utf8.getBytes("UTF-8").length);
System.out.println(utf8.toCharArray().length);
for (int c : utf8.toCharArray()) {
System.out.print(c + " ");
}
System.out.println("\n======utf-8======");
String gbk = new String(s1.getBytes(), Charset.forName("GBK"));
System.out.println(gbk.length());
System.out.println(gbk.getBytes("GBK").length);
System.out.println(gbk.toCharArray().length);
for (int c : gbk.toCharArray()) {
System.out.print(c + " ");
}
System.out.println("\n======gbk======");
String gb2312 = new String(s1.getBytes(), Charset.forName("GB2312"));
System.out.println(gb2312.length());
System.out.println(gb2312.getBytes("GB2312").length);
System.out.println(gb2312.toCharArray().length);
for (int c : gb2312.toCharArray()) {
System.out.print(c + " ");
}
System.out.println("\n======gb2312======");