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

标签 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.

最佳答案

如果您查看 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/

相关文章:

java - StringBuffer 如何在不创建两个对象的情况下实现 append 功能?

java - 仅比较两个实例之间的一个变量

Java 将新列附加到 csv 文件

C : text file, 字符串比较等

c# - 连接数组中所有字符串并用空格分隔的有效方法是什么?

java - 如何获取用户输入(来自扫描仪)并将整个输入转换为 ascii

java - JVM 语言的包

java - Selenium 无法通过 xpath 找到元素

c++ - 查找重叠子串的多个匹配项

c# - 将空格附加到 stringbuilder 左对齐