Java 删除“额外的”;“空的”;字节数组中的字符并转换为字符串
我在这方面做了一段时间,但在这里没有找到任何关于这方面的信息,所以我想我会发布我的解决方案以供批评/使用Java 删除“额外的”;“空的”;字节数组中的字符并转换为字符串,java,arrays,string,byte,concatenation,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
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"));
}
}
import java.lang.*;
公营海螺
{
公共静态void main(字符串[]args)
{
字节[]buf=新字节[256];
int lastGoodChar=0;
//例如,仅将其填满
字节[]fillbuf=(新字符串(“hello”).getBytes();
对于(int i=0;i我相信这也有同样的作用:
String emptyRemoved = "he\u0000llo\u0000".replaceAll("\u0000.*", "");
我称这不是一个真正的问题,因为你在问题中发布了一个解决方案,基本上要求答案是问题/批评。如果你想探索做某事的最佳方式,请正确地将要求定义为一个问题,然后发布你自己问题的答案。这样我们可以上下投票或在c中提出建议omments。是的,对不起。这不是为了问一个问题,而是为了分享代码。我发现这通常会导致更具建设性的批评。而且,作为一个非CS的人,当你不知道如何传达你想要做的事情时,会发现这很有帮助。太棒了,谢谢。我找到了如何替换第二个“for”的方法使用您的建议循环。但它确实需要首先通过指定适当的字符集正确解码字节数组。或者添加:新字符串(content,0,totalBytesRead,“ISO-8859-1”);我想它也会这样做!