Is it possible to add data to a string after adding “\0” (null)?

后端 未结 4 1911
故里飘歌
故里飘歌 2020-12-18 01:16

I have a string that I am creating, and I need to add multiple \"\\0\" (null) characters to the string. Between each null character, is other text data (Just ASCII alphanume

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-18 01:45

    I strongly suspect this is nothing to do with the text in the string itself - I suspect it's just how it's being displayed. For example, try this:

    public class Test {
        public static void main(String[] args) {
            String first = "first";
            String second = "second";
            String third = "third";
            String text = first + "\0" + second + "\0" + third;
            System.out.println(text.length()); // Prints 18
        }
    }
    

    This prints 18, showing that all the characters are present. However, if you try to display text in a UI label, I wouldn't be surprised to see only first. (The same may be true in fairly weak debuggers.)

    Likewise you should be able to use:

     char c = text.charAt(7);
    

    And now c should be 'e' which is the second letter of "second".

    Basically, I'd expect the core of Java not to care at all about the fact that it contains U+0000. It's just another character as far as Java is concerned. It's only at boundaries with native code (e.g. display) that it's likely to cause a problem.

    If this doesn't help, please explain exactly what you've observed - what it is that makes you think the rest of the data isn't being appended.

    EDIT: Another diagnostic approach is to print out the Unicode value of each character in the string:

    for (int i = 0; i < text.length(); i++) {
        System.out.println((int) text.charAt(i));
    }
    

提交回复
热议问题