StringBuilder的indexOf()不返回任何内容

时间:2013-12-19 07:09:47

标签: java string stringbuilder indexof

    StringBuilder builder = new StringBuilder();
    builder.setLength(10);
    builder.append("d");        
    System.out.println(builder.length() + "\t" + builder.toString() + "\t" + builder.indexOf("d"));

输出:

11 

问题:

Why indexOf() doesn't return anything.

我的理解:

 As per my understanding, it should return 10, since StringBuilder is counting the "d" as part of its length in length().
 But in case if "d" is not part of string hold by StringBuilder then, it should return -1 and length should be 10.

1 个答案:

答案 0 :(得分:4)

如果你看一下StringBuilder#setLength(int newLength)

的文档
  

如果newLength参数大于或等于当前长度,则会附加足够的空字符('\ u0000'),以便length成为newLength参数。

这就是为什么在设置长度后附加“d”时,它会放在 10个空字符之后。


  

Q值。为什么indexOf()不返回任何内容。

它确实返回一个值,即10,因为索引是基于 0的。这是代码的输出。

11           d  10         // the 10 represents the index of d
^-length     ^-10 null chars followed by d

您没有获得输出的原因可能是因为您的控制台不支持null个字符。这就是为什么当它遇到空字符\u0000时,它只会停止在控制台中打印值。尝试使用支持打印Unicode字符的eclipse。

示例快照

Output Snapshot

相关问题