3 回答

TA贡献1906条经验 获得超3个赞
你不是在复制最后一个字符。结束索引是一个index,所以它应该指向刚好超过字符串的末尾。正如JavaDoc中所说:
srcEnd
-在要复制的字符串中的最后一个字符之后的索引。
(我的重点)
所以你不想要- 1
after test.length()
。您会看到 的默认值chars[chars.length-1]
,即 0(因为数组被初始化为所有位关闭值)。
所以:
test.getChars(0, test.length(), chars, 0);
// ---------------------------^
为了显示:
{[]}qw
^ ^
| |
| +−−− srcEnd
+−−−−−−−−− srcBegin

TA贡献1835条经验 获得超7个赞
char 数组用值 NULL character 初始化\u0000。打印的原因\u0000是因为您只是复制test.length()-1(独占停止)到chars然后打印所有chars,它\u0000在 index 处test.length()-1。
如果您将代码更新为:
public class TestDS {
public static void main(String[] args) throws Exception {
String test = "{[]}qw";
char[] chars = new char[test.length()];
test.getChars(0, test.length(), chars, 0);
for (char temp : chars) {
System.out.println(temp);
}
}
}
它打印:
{
[
]
}
q
w

TA贡献1820条经验 获得超10个赞
您在获取字符的同时减少了长度。test.getChars(0, test.length() - 1, 字符, 0);
Length 方法:
返回此字符串的长度。长度等于字符串中 Unicode 代码单元的数量。
将其更改为:
test.getChars(0, test.length(), 字符, 0);
添加回答
举报