亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 String 的 getchars() 方法創建的 char 數組的最后一個字符更改為不同的字符

從 String 的 getchars() 方法創建的 char 數組的最后一個字符更改為不同的字符

撒科打諢 2023-06-08 19:42:40
我正在使用 getchars() 方法。代碼沒有像我預期的那樣工作,調試后我發現從 getchars() 方法添加到 char 數組的最后一個字符被更改了。最后一個字符值從傳遞的字符串更改為“\u0000”而不是“w”。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() - 1, chars, 0);? ? ? ? for (char temp : chars) {? ? ? ? ? ? System.out.println(temp);? ? ? ? }? ? }}
查看完整描述

3 回答

?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

你不是在復制最后一個字符。結束索引是一個index,所以它應該指向剛好超過字符串的末尾。正如JavaDoc中所說:

srcEnd-在要復制的字符串中的最后一個字符之后的索引。

(我的重點)

所以你不想要- 1after?test.length()。您會看到 的默認值chars[chars.length-1],即 0(因為數組被初始化為所有位關閉值)。

所以:

test.getChars(0, test.length(), chars, 0);

// ---------------------------^

為了顯示:


{[]}qw

^? ? ?^

|? ? ?|

|? ? ?+??? srcEnd

+????????? srcBegin


查看完整回答
反對 回復 2023-06-08
?
qq_花開花謝_0

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


查看完整回答
反對 回復 2023-06-08
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

您在獲取字符的同時減少了長度。test.getChars(0, test.length() - 1, 字符, 0);

Length 方法
返回此字符串的長度。長度等于字符串中 Unicode 代碼單元的數量。

將其更改為

test.getChars(0, test.length(), 字符, 0);


查看完整回答
反對 回復 2023-06-08
  • 3 回答
  • 0 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號