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

十年热恋 提交于 2019-12-13 14:07:42

问题


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.


回答1:


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:


You can use trim() to remove space chars:

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



回答3:


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());


来源:https://stackoverflow.com/questions/13027588/converting-a-c-ctyle-string-encoded-as-a-character-array-to-a-java-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!