length public int length()返回此字符串的长度。长度等于字符串中 Unicode 代码单元的数量。 指定者: 接口 CharSequence 中的 length 返回: 此对象表示的字符序列的长度。个数,不是字节数。
/** The value is used for character storage. */ private final char value[]; //你在纠结里面每个char占几个字节 /** The offset is the first index of the storage that is used. */ private final int offset; /** The count is the number of characters in the String. */ private final int count; //而length返回的是它 /** Cache the hash code for the string */ private int hash; // Default to 0
楼主没看过API吗?
public int length()返回此字符串的长度。长度等于字符串中 Unicode 代码单元的数量。 指定者:
接口 CharSequence 中的 length
返回:
此对象表示的字符序列的长度。个数,不是字节数。
private final char value[]; //你在纠结里面每个char占几个字节 /** The offset is the first index of the storage that is used. */
private final int offset; /** The count is the number of characters in the String. */
private final int count; //而length返回的是它 /** Cache the hash code for the string */
private int hash; // Default to 0
你看下java是怎么定义str.length的,就知道应该是6,还是12了。
String s = "a";
字节长度s.getBytes().length=1
char c = 'a'
c是占两个字节的,String内部是以char形式存放的,也就是说s的内部char是占两个字节的
为什么s.getBytes().length得到的不是char的字符长度?
String s = "a";
字节长度s.getBytes().length=1
char c = 'a'
c是占两个字节的,String内部是以char形式存放的,也就是说s的内部char是占两个字节的
为什么s.getBytes().length得到的不是char的字节长度?我问的是字节长度,不是字符长度,多谢各位
=======================提问=============================
Java 中的 char 代表一个“UNICODE 字符(宽字节字符)”
也就是说任何字符如“a”,在char中都是以两个字节存储的,即[0,97],
但是为什么用String.getBytes()默认编码取时不能得到[0,97],而只能得到[97]呢?
==============================================================================
请大家帮忙解答最后提问的问题,多谢
=======================提问=============================
Java 中的 char 代表一个“UNICODE 字符(宽字节字符)”
也就是说任何字符如“a”,在char中都是以两个字节存储的,即[0,97],
但是为什么用String.getBytes()默认编码取时不能得到[0,97],而只能得到[97]呢?
========================================================
java中char都是以UNICODE 字符(宽字节字符)存放的
String.getBytes(encoding)返回byte流时,是以encoding的格式返回的;
每个encoding 得到的字节流是不一样的
如:String str="a"; //内部是char[0]='a' ,以[0,97]两个字节存放;
str.getBytes("gbk") 得到的byte流为:97
str.getBytes("utf-8") 得到的byte流为:97
str.getBytes("utf-16") 得到的byte流为:-2 -1 0 97 大家可以补充