从字节数组中删除额外的"空"字符并转换为字符串

use*_*880 5 java arrays string byte concatenation

我正在研究这个问题一段时间,并且在这里没有找到任何关于此的内容,所以我想我会发布我的批评/有用的解决方案.

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"));
    }    
}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 11

我相信这也是一样的:

String emptyRemoved = "he\u0000llo\u0000".replaceAll("\u0000.*", "");
Run Code Online (Sandbox Code Playgroud)