更新时间:2023-02-09 20:04:49
有没有必要到这里涉及到一个字符串。只需复制到一个新的数组,它是一个字符比你输入数组短。使用此任务的方法是 Arrays.copyOf
。
There is no need for a String to get involved here. Just copy into a new array that is one char shorter than your input array. The method to use for this task is Arrays.copyOf
.
原因你的输出是越野车是因为在Java字符串有无关空终止符。您code的第一行创建一个字符串,它的最后一个字符是空字符。
The reason your output is buggy is because strings in Java have nothing to do with null-terminators. Your first line of code creates a string whose last character is the null-character.
如果您有垃圾继空字符,你可以使用新的String(inputArray)
,然后找到空字符与字符串。的indexOf('\\ 0')
和使用,在 String.substring
操作切出不需要的部分。然而,这将是简单还是(从时间/空间复杂度的角度),只是迭代这个数组找到空字符,然后用 Arrays.copyOf
与指数作为分界点。
If you have garbage following the null-char, you can use new String(inputArray)
, then find the null-char with String.indexOf('\0')
and use that in a String.substring
operation to cut out the unneeded part. However, it would be still simpler (from the time/space complexity perspective) to just iterate over the array to locate the null-char and then use Arrays.copyOf
with that index as cutoff point.