How can I convert from byte array to string in Java removing padding characters?

Viewed 657

I have a byte array which contains text padded with values 0 up to fill 16 bytes.

When I try to convert it to String I can not get the right length/String, it always retrieves the whole 16 characters.

I have tried:

import java.nio.charset.StandardCharsets;

public class HelloWorld{

     public static void main(String []args){

        // SIMULATED BYTE[] CONTAINS "ABC" PLUS CHAR(0) UNTIL FILL 16 BYTES
        byte[] name = new byte[16]; 
        for(int i=0; i<16; i++) {
            name[i] = 0;
        }
        name[0] = 'A';
        name[1] = 'B';
        name[2] = 'C';

        // DESIRED OUTPUT IS A STRING = "ABC".
        // I.E. REMOVAL OF PADDING WITH CHAR(0)s
        String nameStr = new String(name, StandardCharsets.US_ASCII);

        System.out.println("#"+nameStr+"#");
        System.out.println(nameStr.length());

     }
}

This is the output:

output

The desired retrieved length is 3, not 16. Also it can be seen in NetBeans output how the String contains the padding 0 values.

I am using OpenJDK8 under FreeBSD and NetBeans 11.

3 Answers

The straight-forward approach is to identify the trailing zeros and specify a range to the String constructor:

int end = name.length;
while(end > 0 && name[end - 1] == 0) end--;
String nameStr = new String(name, 0, end, StandardCharsets.US_ASCII);

replaceall

Update the string and remove unwanted characters

String nameStr = new String(name, StandardCharsets.US_ASCII).replaceAll("\0", "");

, output

#ABC#

You can trim the string

String nameStr = new String(name, StandardCharsets.US_ASCII).trim();

System.out.println("#" + nameStr + "#");
System.out.println(nameStr.length());

Output

#ABC#
3
Related