【问题标题】:Removing extra "empty" characters from byte array and converting to a string [closed]从字节数组中删除额外的“空”字符并转换为字符串 [关闭]
【发布时间】:2011-04-20 22:40:03
【问题描述】:

我在这方面工作了一段时间,但在这里没有找到任何相关信息,所以我想我会发布我的解决方案以供批评/有用。

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

【问题讨论】:

  • 我称这不是一个真正的问题,因为您在问题中发布了一个解决方案,基本上要求答案是问题/批评。如果您想探索做某事的最佳方式,请将需求正确定义为一个问题,然后发布您自己问题的答案。这样我们就可以投票赞成/反对或在 cmets 中提出建议。
  • 是的,对不起。这并不是要问一个问题,而是要共享代码。我发现这经常会导致更具建设性的批评。而且,作为一名非 CS 人员,当您不知道如何传达自己想做的事情时,会发现它会有所帮助。

标签: java arrays string byte concatenation


【解决方案1】:

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

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

【讨论】:

  • 太棒了,谢谢。我想出了如何使用您的建议替换第二个“for”循环。但它确实需要首先通过指定适当的字符集来正确解码字节数组。
  • 或添加:new String(content, 0, totalBytesRead, "ISO-8859-1");我认为它也一样!
猜你喜欢
  • 2019-02-28
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多