java toCharArray() 方法会改变定义数组时的长度

目的:想要使用 String 类的 toCharArray() 方法,且数组长度大于字符串的长度

 String s = "123456789";
 System.out.println("s.length() : " + s.length());
 
 char[] str = new char[s.length() + 1];
 int expectedLength = str.length;
 System.out.println("expectedLength : " + expectedLength);
 str = s.toCharArray();
// str[s.length()] = '\0';
 int trueLength = str.length;
 System.out.println("trueLength : " + trueLength);
 
================ 结果 ==================
s.length() : 9
expectedLength : 10
trueLength : 9
		

然并卵,原本想要将字符串转化为字符数组之后,在字符数组中添加新的字符(添加 ‘\0’ ),但是转变之后字符数组长度和字符串长度相等

查看源码后发现关于 toCharArray() 方法解释为
查看源码的方法

 /**
     * Converts this string to a new character array.
     *
     * @return  a newly allocated character array whose length is the length
     *          of this string and whose contents are initialized to contain
     *          the character sequence represented by this string.
     */
    public char[] toCharArray() {
        return isLatin1() ? StringLatin1.toChars(value)
                          : StringUTF16.toChars(value);
    }

即返回的是一个新的字符数组,该字符数组的长度与字符串长度相等。也就是说使用toCharArray()会改变原来定义的数组的指向
指向改变了为了达到字符串中字符都存储在字符数组中并且字符数组长度大于字符串的目的:

// 将字符串转变为字符数组,并且字符数组长度大于字符串长度
// 该方法中字符数组为 10 
   int sLength = s.length();
   for (int i = 0; i < sLength; i++) 
       str[i] = s.charAt(i);
   str[sLength] = '\0';
// 注意:如果通过 System.out.println(str); 打印数组,'\0' 并不会打印出来
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值