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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3857803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:43:23  来源:igfitidea点击:

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

javaarraysstringbyteconcatenation

提问by user460880

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"));
    }    
}

回答by aioobe

I believe this does the same thing:

我相信这会做同样的事情:

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