StringBuffer.replace javadoc

StringBuffer.replace javadoc

我对官方 Javadoc 感到困惑

public StringBuffer replace(int start, int end, String str)

Replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start. (This sequence will be lengthened to accommodate the specified String if necessary.)

"if no such character exists" 是什么意思?

如果我执行以下操作

StringBuffer sb = new StringBuffer("                                                  "); // 30 whitespace characters
sb.replace(3, 20, "123456789012345678901234567890");

我最终得到字符串 " 123456789012345678901234567890 "

我本来期望 " 12345678901234567 " (length = 30),因为我说过要将 "source" StringBuffer 中的字符从字符 3 替换为 20 (20-3 = 17)。

我试过查看 OpenJDK 实现,但我不能说它有帮助(我不明白为什么 System.arraycopy 是用 srcpos = end, srcpos 调用的)。

Javadocs 将效果明确描述为 "First the characters in the substring [actually, subsequence] are removed"。这意味着原始序列中从索引 3 到索引 19 的字符(所有空格)都将被删除,一端保留示例中的前三个字符,另一端保留最后十个字符。正如您所猜测的那样,文档没有提到使用替换字符串的子字符串。事实上,他们明确指出 "then the specified String is inserted at start." 整个替换 String,而不仅仅是适合的部分。所以现在你有三个空格加上三十个字符的替换加上结果中的十个空格。

"If no such character exists" 表示如果end 大于原始序列长度,不会发生错误,只是将原始序列的其余部分全部删除。因此,如果您的原始序列的长度为 10,则从索引 3 包含的内容移除到 20 排除的内容会在替换之前从索引 3 上删除所有序列的字符。