删除多余的“空”字节数组中的字符并转换为字符串 [英] Removing extra "empty" characters from byte array and converting to a string
本文介绍了删除多余的“空”字节数组中的字符并转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我花了一段时间,在这里没有找到任何关于这个的信息,所以我想我会发表批评或有用的解决方案。
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"));
}
}
推荐答案
I相信这会做同样的事情:
I believe this does the same thing:
String emptyRemoved = "he\u0000llo\u0000".replaceAll("\u0000.*", "");
这篇关于删除多余的“空”字节数组中的字符并转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文