I am confused by the official Javadoc which says
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.)
What does "if no such character exists" mean ?
If I do the following
StringBuffer sb = new StringBuffer(" "); // 30 whitespace characters
sb.replace(3, 20, "123456789012345678901234567890");
I end up with the string " 123456789012345678901234567890 "
.
I would have expected " 12345678901234567 "
(length = 30), because I said to replace characters in the "source" StringBuffer from character 3 to 20 (20-3 = 17).
I have tried looking at OpenJDK implementation but I can't say it helped (I don't understand why System.arraycopy is called with srcpos = end, srcpos).
The Javadocs explicitly describe the effect as "First the characters in the substring [actually, subsequence] are removed". That means that the characters from index 3
to index 19
in the original sequence (all blanks) are removed, leaving the first three characters from your example on one end and the last ten on the other. The docs say nothing about taking a substring of the replacement string, as you surmised. Indeed, they explicitly state that "then the specified String
is inserted at start." The whole replacement String
, not just the part that would have fit. So now you have three blanks plus the thirty-character replacement plus ten blanks in the result.
"If no such character exists" means if end
is larger than the original sequence length, no error occurs, just the whole rest of the original sequence is removed. So if your original sequence had been of length ten, then removing from index 3
inclusive to 20
exclusive would remove all the sequence's characters from index 3
on, before replacement.