简体   繁体   English

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

[英]indexOf() of StringBuilder doesn't return anything

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

Output: 输出:

11 

Problem: 问题:

Why indexOf() doesn't return anything.

My Understanding: 我的理解:

 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.

If you look at the docs of StringBuilder#setLength(int newLength) 如果你看一下StringBuilder#setLength(int newLength)的文档StringBuilder#setLength(int newLength)

If the newLength argument is greater than or equal to the current length, sufficient null characters ('\') are appended so that length becomes the newLength argument. 如果newLength参数大于或等于当前长度,则会附加足够的空字符('\\ u0000'),以便length成为newLength参数。

That is why when you append "d" after setting the length, it is placed after the 10 null characters . 这就是为什么在设置长度后附加“d”时,它会放在10个空字符之后


Q. Why indexOf() doesn't return anything. 问:为什么indexOf()不返回任何内容。

It does return a value and that is 10 , since the indexing is 0-based . 它确实返回一个值,即10 ,因为索引是从0开始的 This is the output of your code. 这是代码的输出。

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

The reason you're not getting the output may be because of your console not supporting null characters. 您没有获得输出的原因可能是您的控制台不支持null字符。 That is why, when it encounters the null character \ , it would just stop printing the values in the console. 这就是为什么当它遇到空字符\ ,它只会停止在控制台中打印值。 Try using eclipse which supports printing of Unicode characters. 尝试使用支持Unicode字符打印的eclipse。

Sample snapshot : 示例快照

输出快照

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM