4个字符 “我们”算几个字符?
计算字符串的字节数:
getBytes()length//UTF-8编码下一个字占3个字节
getBytes("gb2312").length//gb2312编码下一个字占2个字节
public byte[] getBytes(Charset charset) {
String canonicalCharsetName = charset.name();
if (canonicalCharsetName.equals("UTF-8")) {
return Charsets.toUtf8Bytes(value, offset, count);
} else if (canonicalCharsetName.equals("ISO-8859-1")) {
return Charsets.toIsoLatin1Bytes(value, offset, count);
} else if (canonicalCharsetName.equals("US-ASCII")) {
return Charsets.toAsciiBytes(value, offset, count);
} else if (canonicalCharsetName.equals("UTF-16BE")) {
return Charsets.toBigEndianUtf16Bytes(value, offset, count);
} else {
CharBuffer chars = CharBuffer.wrap(this.value, this.offset, this.count);
ByteBuffer buffer = charset.encode(chars.asReadOnlyBuffer());
byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes);
return bytes;
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
本文将用3个图片来解释Java中String的不可变性().
1. 声明String对象
String s = "abcd";
String s2 = s;
s = s.concat("ef"); // s = s + "ef"; // 等价