从字节数组中删除多余的“空”字符并转换为字符串

7
我花了一些时间研究这个问题,但在这里没有找到任何相关的内容,所以我想发表我的解决方案供批评/有用性。
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"));
    }    
}

我认为这不是一个真正的问题,因为您在问题中发布了解决方案,基本上要求回答者提出问题/批评。如果您想探索最佳实践,应该将需求定义清楚并作为一个问题发布,然后再发布自己的答案。这样我们就可以通过投票和评论提出建议。 - Mark Peters
是的,抱歉。这并不是要问一个问题,而是分享代码。我发现这通常会导致更多建设性的批评。作为一个非计算机科学专业的人,当你不知道如何表达你想做什么时,这样做会有所帮助。 - user460880
1个回答

13

我相信这个也可以达到同样的效果:

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

太棒了,谢谢。我已经通过你的建议找到了如何替换第二个“for”循环。但是这确实需要首先通过指定正确的字符集来正确解码字节数组。 - user460880
1
或者添加:new String(content, 0, totalBytesRead, "ISO-8859-1");我认为它做的是同样的事情! - cesards

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接