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);
}
}
}
它打?。?/p>
{
[
]
}
q
w

TA貢獻1820條經驗 獲得超10個贊
您在獲取字符的同時減少了長度。test.getChars(0, test.length() - 1, 字符, 0);
Length 方法:
返回此字符串的長度。長度等于字符串中 Unicode 代碼單元的數量。
將其更改為:
test.getChars(0, test.length(), 字符, 0);
添加回答
舉報