Converting a C-ctyle string encoded as a character array to a Java String

4.2k Views Asked by At

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.

3

There are 3 best solutions below

2
On BEST ANSWER

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 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.

2
On

You can use trim() to remove space chars:

System.out.println(Arrays.toString(toRet.trim().toCharArray()));
2
On

To confuse people that have to maintain your code, you could write:

char[] dta = new char[]{'B','A','D','\0', 'G', 'A', 'R', 'B', 'A', 'G', 'E'};

String string = (dta[0] == '\0') ? "" : (new String(dta)).split("\0")[0];
System.out.println(string.toCharArray());