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

Jonathan Beaudoin
  • 2,158
  • 4
  • 27
  • 63

2 Answers2

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.

nickb
  • 59,313
  • 13
  • 108
  • 143
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

romeara
  • 1,426
  • 1
  • 17
  • 26