String.length()是表示字符串所需的UTF-16代码单元的数量。也就是说,它是用于表示字符串的char值的数量,因此等于toCharArray().length。
String.getBytes().length是在平台的默认编码中表示字符串所需的字节数。
public class test {
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "哈哈哈hhh./ ";
System.out.println(s.length());
System.out.println(s.getBytes().length);// 与编译器使用的编码相同
System.out.println("UTF-8:" + s.getBytes("UTF-8").length);// 中文占3个字节,其余1个字节
System.out.println(s.getBytes("GB2312").length);// 与GBK相同
System.out.println("GBK:" + s.getBytes("GBK").length);// 中文占2个字节,其余1个字节
}
}