java - StringBuffer.替换javadoc

标签 java stringbuilder stringbuffer

我对官方 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.)

“如果不存在这样的字符”是什么意思?

如果我执行以下操作

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

我最终得到字符串“123456789012345678901234567890”

我本来期望“12345678901234567”(长度= 30),因为我说过将“源”StringBuffer中的字符从字符3替换为20(20-3 = 17)。

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

最佳答案

Javadocs 明确地将效果描述为“首先删除子字符串 [实际上是子序列] 中的字符”。这意味着原始序列中从索引 3 到索引 19 的字符(全部为空白)将被删除,将示例中的前三个字符保留在一端,最后一个字符保留在示例中。另一个是十个。正如您所猜测的,文档没有提到如何获取替换字符串的子字符串。事实上,他们明确指出“然后在开始时插入指定的String”。整个替换String,而不仅仅是适合的部分。所以现在结果中有三个空格加上三十个字符的替换加上十个空格。

“如果不存在这样的字符”表示如果end大于原始序列长度,则不会发生错误,只是删除原始序列的其余部分。因此,如果原始序列的长度为 10,那么从索引 3(含)删除到 20(排除)将会删除索引 3 中的所有序列字符。开启,更换前。

关于java - StringBuffer.替换javadoc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43800347/

相关文章:

java - 如何打开 java 字符串枚举中定义的值

java - 在 Java 中完成 mysql 查询之前停止执行 Java 代码?

java - StringBuffer toString() 不打印任何内容

Java:计算 HashMap<String, ArrayList<String>> 中的项目总数

java - 如何使用 okhttp 执行 Reddit 帖子

java - Java 基准测试(比较两个类)

java - 当子字符串多于值时,将重复出现的子字符串替换为数组值

C# 字符串连接最佳实践

java - Java 中 String 的 StringBuilder