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()));
But the result is incorrect, and in fact oddly buggy. Here's what the above code outputs:
[B, A, D,
And here's what I want
[B, A, D]
I'm running on openJdk6 on Ubuntu. I haven't tested the above code on other VM's.
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
.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.
Response to your updated question
If you have garbage following the null-char, you can use
new String(inputArray)
, then find the null-char withString.indexOf('\0')
and use that in aString.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 useArrays.copyOf
with that index as cutoff point.