为了账号安全,请及时绑定邮箱和手机立即绑定

从 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);

        }

    }

}

它打印:


{

[

]

}

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 关注
  • 189 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号