来自 String 类:
public String(byte[] bytes,
int offset,
int length)
Java 文档:
Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.
The length of the new String is a function of the charset, and hence may not be equal to the length of the subarray.
The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.
粗体部分是什么意思?
最佳答案
The length of the new String is a function of the charset, and hence may not be equal to the length of the subarray.
在某些字符集中,某些甚至所有字符都使用多个字节。因此给定长度的数组可能会产生较短的字符串。不要假设 1 个字节 = 1 个字符。
The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.
如果您使用某些字符集解码字符串,并且字节数组包含该字符集未知的值,则会出现未定义的行为。例如,如果字符集使用 0 到 127 之间的值,并且您的数组包含值 -5,则会出现未定义的行为。
关于Java 字符串构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50375313/