gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:26:44 25 4
gpt4 key购买 nike

    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.

最佳答案

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

If the newLength argument is greater than or equal to the current length, sufficient null characters ('\u0000') are appended so that length becomes the newLength argument.

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


Q. Why indexOf() doesn't return anything.

它确实返回了一个值,即 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

关于java - StringBuilder 的 indexOf() 不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20675457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com