1

I ran into an issue when creating a String from a byte array where values of 0 inside the array are ignored when constructing the string. How can I make it so that if the byte value is 0, the String simply adds a space instead of removing it.

Example, the output of this is DT_TestTracelineCTestTraceli.

public static void main(String[] args) {
    byte[] text = {68, 84, 95, 84, 101, 115, 116, 84, 114, 97, 99, 101, 108, 105, 110, 101, 0, 0, 0, 0, 67, 84, 101, 115, 116, 84, 114, 97, 99, 101, 108, 105};
    System.out.println(new String(text));
}

How can I make it so I can separate those two strings using a tab character or uses spaces so the output is DT_TestTraceline CTestTraceli

Thanks

4
  • 2
    I believe you should also tell us which encoding you are using to decode the byte array. Commented Dec 22, 2015 at 0:31
  • I'm reading the bytes from memory directly into a byte array. Commented Dec 22, 2015 at 0:33
  • I tested the code the output is: DT_TestTraceline CTestTraceli Commented Dec 22, 2015 at 0:36
  • 1
    Possible duplicate of What is character encoding and why should I bother with it Commented Dec 22, 2015 at 0:39

2 Answers 2

9

You should be specifying an encoding to new String() - Without one, you're using the platform default (which makes your code much less portable, as now you're making assumptions about the environment you're executing on).

Assuming you're using UTF-8, you can replace all of your zeroes with 32, the UTF-8 code for the space character, and it should work:

for(int i = 0; i < text.length; i++) {
    if(text[i] == 0) {
        text[i] = 32; 
    }
}
String result = new String(text, StandardCharsets.UTF_8);

You can see it working on ideone.

Sign up to request clarification or add additional context in comments.

Comments

4

One way would be to iterate over the array before turning it into a string and replacing '0' characters with the character code for space in whatever character encoding you are using

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.