日期:2014-05-20  浏览次数:21158 次

byte转String时怎样把byte中结尾的0取掉???
byte[] test = new byte[36];
test[0] = 'A';
test[1] = 'D';
String teststr = new String(test);
teststr.trim();
int Len = teststr.length();

test[2]到test[35]都是0.
专成teststr 后,变量查看是"AD                         ".
trim无效
Len还是等于36.

怎样才能把后面的0取掉???

------解决方案--------------------
	byte[] test = new byte[36];
test[0] = 'A';
test[1] = 'D';
String teststr = "";
for (byte b: test) {
if (b != 0) {
teststr += (char)b;
}
}
int len = teststr.length();
System.out.println(len);
System.out.println(teststr);


------解决方案--------------------
转换了之后 这个string 变成
"AD\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000....."
\u0000 在unicode中查是 NUL
而trim 检测的是 \u0020也就是空格。 所以估计trim不掉吧。 

用 System.out.println(teststr.indexOf('\u0000'));能看到 第几位是 这个NUL
然后用 
teststr = teststr.substring(0,teststr.indexOf('\u0000')); 来截取就好了。
------解决方案--------------------


你也可以从最后一位开始判断,直到遇到一个字符不等于0的字符,然后记住这个位置。