目的:想要使用 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' 并不会打印出来