Removing extra "empty" characters from an array of bytes and converting to a string

I worked on this for a while and did not find anything about it here, so I decided to publish my solution for criticism / usefulness.

import java.lang.*;
public class Concat
{    
    public static void main(String[] args)
    {
        byte[] buf = new byte[256];
        int lastGoodChar=0;

        //fill it up for example only
        byte[] fillbuf=(new String("hello").getBytes());
        for(int i=0;i<fillbuf.length;i++) 
                buf[i]=fillbuf[i];

        //Now remove extra bytes from "buf"
        for(int i=0;i<buf.length;i++)
        {
                int bint = new Byte(buf[i]).intValue();
                if(bint == 0)
                {
                     lastGoodChar = i;
                     break;
                }
        }

        String bufString = new String(buf,0,lastGoodChar);
        //Prove that it has been concatenated, 0 if exact match
        System.out.println( bufString.compareTo("hello"));
    }    
}
+3
source share
1 answer

I believe this does the same:

String emptyRemoved = "he\u0000llo\u0000".replaceAll("\u0000.*", "");
+8
source

Source: https://habr.com/ru/post/1767926/


All Articles