【问题标题】:indexOf() of StringBuilder doesn't return anythingStringBuilder 的 indexOf() 不返回任何内容
【发布时间】:2013-12-19 07:09:46
【问题描述】:
    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.

【问题讨论】:

    标签: java string stringbuilder indexof


    【解决方案1】:

    如果您查看StringBuilder#setLength(int newLength) 的文档

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

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


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

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

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

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

    示例快照

    【讨论】:

    • 但在打印语句中,我有indexOf(),但我没有得到返回值。我重新运行代码,现在也只有 11 个输出。
    • 虽然我没有发现eclipse控制台有什么问题,但是为了重新验证输出,我会在命令行上尝试,如果输出和你解释的一样,那么,我会接受你的回答
    猜你喜欢
    • 2010-10-09
    • 2020-04-27
    • 2019-04-06
    • 2012-02-15
    • 2020-09-07
    • 2021-11-22
    • 2015-11-06
    • 2013-11-14
    • 2014-03-23
    相关资源
    最近更新 更多