Terminate a char[] -> String conversion midway via a null pointer

五迷三道 提交于 2019-12-10 14:47:52

问题


I'm trying to replicate this in Java. To save you the click, it says that a character array ['F', 'R', 'A', 'N', 'K', NULL, 'k', 'e', 'f', 'w'], when converted to a null-terminated string, will stop after 'K', since it encounters a null pointer there. However, my Java attempts don't seem to be working.

public class TerminatingStrings{
    public static void main(String[] args){
        char[] broken = new char[3];
        broken[0] = 'a';
        broken[1] = '\u0000';
        broken[2] = 'c';
        String s = new String(broken);
        System.out.println(s);
    }
}

Still prints ac. Aside from this I've also tried (1) not initializing broken[1] and (2) explicitly setting it to null, at attempt which didn't even compile.

Is this possible at all in Java? Or maybe my understanding of things is wrong?


回答1:


Unlike C, Java does not use NUL-terminated strings. To get the behaviour, your code has to find the location of the first \0 in the char array, and stop there when constructing the string.



来源:https://stackoverflow.com/questions/10935430/terminate-a-char-string-conversion-midway-via-a-null-pointer

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