【问题标题】:is there a bug in java new String [closed]java new String中是否有错误[关闭]
【发布时间】:2016-01-27 09:48:30
【问题描述】:

我试试这个代码:

byte[] data = new byte[66000];
int count = is.read(data);
String sRequest = new String(data);  //will received byte array hello
String all = sRequest;        
all = all.concat("world");
System.out.println(all);

它只打印到我的控制台:hello

concat java的函数有bug吗?我还使用 + 运算符而不是 concat 函数,但结果相同:( 如何将字符串与字节数组中的新字符串连接起来?

【问题讨论】:

  • 您确定这正是您正在测试的代码吗?我无法重现这个。
  • 您应该注意的一点是,结果字符串的长度为 66005,因为它包含了数组中 helloworld 之间的所有空值。
  • 我也是。可能会在这一行上方给我们一些您的代码...
  • 您忽略了返回的字节数。注意:并非所有字符都是可打印的,因此您不能总是期望看到它们。

标签: java concat


【解决方案1】:

代替

    String sRequest = new String(data);  //will received byte array hello

使用

    String sRequest = new String(data, 0, count);  //will received byte array hello

当您额外打印结果字符串的长度时,您会注意到差异:

    System.err.println(all + "/" + all.length());

在第一种情况下给出helloworld/66005,在第二种情况下给出helloworld/10。您只看到“hello”的原因可能是您的控制台的问题 - 在 Eclipse 中,我确实看到了“helloworld”,但是当我将其复制并粘贴到另一个编辑器中时,只使用了一个单词。初始数组中的0 值是结果的一部分(因为它们已经被添加到第一个字符串中),但它们不会被打印出来(因为它们不是可打印的字符)。

【讨论】:

  • 太好了,效果很好
猜你喜欢
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
  • 2012-03-27
  • 2018-06-19
  • 1970-01-01
  • 2017-06-06
相关资源
最近更新 更多