转换一个C-ctyle字符串连接codeD作为字符数组Java的String [英] Converting a C-ctyle string encoded as a character array to a Java String
问题描述
我有一个C风格的字符串连接codeD作为Java的字符数组,但我想这个数组转换成Java的String。我试图使用匹配的构造函数调用,
I have a C-style string encoded as an array of characters in Java, but I would like to convert this array to a Java String. I tried using the matching constructor call,
String toRet = new String(new char[]{'B','A','D','\0', 'G', 'A', 'R', 'B', 'A', 'G', 'E'});
System.out.println(Arrays.toString(toRet.toCharArray()));
但结果是不正确的,事实上奇怪手推车。下面是上面code输出:
But the result is incorrect, and in fact oddly buggy. Here's what the above code outputs:
[B, A, D,
这就是我想要的。
[B, A, D]
我在openJdk6 Ubuntu上运行。我没有测试过的其他虚拟机上面的code。
I'm running on openJdk6 on Ubuntu. I haven't tested the above code on other VM's.
推荐答案
有没有必要到这里涉及到一个字符串。只需复制到一个新的数组,它是一个字符比你输入数组短。使用此任务的方法是 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.
这篇关于转换一个C-ctyle字符串连接codeD作为字符数组Java的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!