Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing extra "empty" characters from byte array and converting to a string [closed]

I was working on this for a while and did not find anything about this on here, so I thought I would post 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"));
    }    
}
like image 205
user460880 Avatar asked Oct 04 '10 17:10

user460880


People also ask

Can we convert byte array to string?

We can convert the byte array to String for the ASCII character set without even specifying the character encoding. The idea is to pass the byte[] to the string.

Can we convert byte array to string in Java?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.


1 Answers

I believe this does the same thing:

String emptyRemoved = "he\u0000llo\u0000".replaceAll("\u0000.*", "");
like image 85
aioobe Avatar answered Oct 06 '22 00:10

aioobe