Sub topic 4
Inserting, Deleting, Replacing and Reversing
This chapter assumes you can already create a StringBuilder and call append and toString, as covered in the previous chapter. It also assumes you know that String is immutable. Here you will learn the methods that edit text already in a builder, the index rules they follow, and the mistakes people make with them.
Editing in place
A String never changes after creation, so every "edit" produces a new object. A StringBuilder is mutable. Its editing methods change the characters inside the same object, and most of them return this, so you can chain calls.
| Method | What it does | Valid range |
|---|---|---|
| `insert(int offset, X value)` | Inserts text before position `offset` | `0 <= offset <= length()` |
| `delete(int start, int end)` | Removes characters from `start` up to but not including `end` | `0 <= start <= length()` and `start <= end`. An `end` past the length is clamped. |
| `deleteCharAt(int index)` | Removes one character | `0 <= index < length()` |
| `replace(int start, int end, String str)` | Removes `start` to `end - 1`, then inserts `str` there | Same as `delete` |
| `setCharAt(int index, char c)` | Overwrites one character. It returns `void`. | `0 <= index < length()` |
| `reverse()` | Reverses the contents | None |
| `setLength(int n)` | Truncates, or pads with `'\0'` | `n >= 0` |
Every range is half-open: the start index is included and the end index is excluded. This matches String.substring.
A first walkthrough
The following program applies four edits to one builder. The comments show what System.out.println prints after each step.
public class EditDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World");
sb.insert(5, "!!!");
System.out.println(sb); // Hello!!!, World
sb.replace(0, 5, "Howdy");
System.out.println(sb); // Howdy!!!, World
sb.delete(5, 8);
System.out.println(sb); // Howdy, World
sb.reverse();
System.out.println(sb); // dlroW ,ydwoH
}
}Each method works on the result of the one before it, so indexes refer to the builder's current contents, not the original text. After the replace, the three exclamation marks sit at indexes 5, 6 and 7. That is why delete(5, 8) removes exactly them. When you plan several edits in a row, recompute the positions after each one, or edit from the end of the text toward the start so earlier positions stay valid.
Because these methods return the builder, the same program could be written as one chain:
String result = new StringBuilder("Hello, World")
.insert(5, "!!!")
.replace(0, 5, "Howdy")
.delete(5, 8)
.reverse()
.toString();
System.out.println(result); // dlroW ,ydwoHsetCharAt is the exception. It returns void, so it must end a chain or stand on its own line.
insert in detail
insert has overloads for most types, like append: String, char, int, long, double, boolean, char[], CharSequence and Object. The new text goes before the character currently at offset. Two offsets are worth remembering:
insert(0, x)adds text at the front.insert(sb.length(), x)is the same asappend(x).
The overload is chosen by the static type of the argument, which causes one common surprise. sb.insert(0, 'A') inserts the character A, but sb.insert(0, 65) inserts the two characters 65, because 65 is an int and is converted to its decimal text. If you want a character from a code, cast it: sb.insert(0, (char) 65).
Inserting near the front is not free. The builder must shift every character after the insertion point to make room, so the cost grows with the length of the text that follows. One insertion into a short string is harmless. Thousands of insert(0, ...) calls on a large builder add up. If you only add at the end, append avoids the shifting.
delete and deleteCharAt
delete(start, end) removes the characters at indexes start through end - 1. deleteCharAt(index) removes one. The two methods have different rules for out-of-range values, and the next section shows them in action.
replace is positional
StringBuilder.replace(int, int, String) differs from String.replace in two ways:
- It takes a range of indexes, not text to search for.
- The replacement can be longer or shorter than the range it replaces, so the builder grows or shrinks.
Replacing a range with an empty string is the same as deleting it. Replacing an empty range (where start == end) is the same as inserting.
There is no replaceAll on StringBuilder. If you need to replace every occurrence of some text, you must search with indexOf and replace by position. A sample implementation appears later in this chapter.
Range rules and exceptions
The edit methods report invalid positions with StringIndexOutOfBoundsException, an unchecked exception. The surprising part is that delete and replace are lenient about the end index but strict about the start index.
public class RangeRules {
static void attempt(String name, Runnable action) {
try {
action.run();
System.out.println(name + " ok");
} catch (StringIndexOutOfBoundsException e) {
System.out.println(name + " -> StringIndexOutOfBoundsException");
}
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("abcdef");
sb.delete(3, 100); // end is clamped to length: "abc"
sb.replace(1, 100, "XYZ"); // end is clamped too: "aXYZ"
System.out.println(sb);
attempt("insert(4)", () -> sb.insert(4, "!")); // offset == length is allowed
attempt("insert(6)", () -> sb.insert(6, "?")); // length is now 5
attempt("deleteCharAt(5)", () -> sb.deleteCharAt(5));
attempt("delete(3, 1)", () -> sb.delete(3, 1)); // start > end
attempt("delete(5, 5)", () -> sb.delete(5, 5)); // empty range at the end
System.out.println(sb);
}
}The output is:
aXYZ
insert(4) ok
insert(6) -> StringIndexOutOfBoundsException
deleteCharAt(5) -> StringIndexOutOfBoundsException
delete(3, 1) -> StringIndexOutOfBoundsException
delete(5, 5) ok
aXYZ!The same behavior applies to replace. The clamped end index is convenient when you mean "delete everything from here to the end", but it can also hide an off-by-one error, because a mistaken end of length() + 1 does not fail.
Overwriting with setCharAt
setCharAt replaces a single char without changing the length. It suits character-by-character transformations such as masking:
public class MaskDemo {
public static void main(String[] args) {
String card = "4111111111111111";
StringBuilder sb = new StringBuilder(card);
for (int i = 0; i < sb.length() - 4; i++) {
sb.setCharAt(i, '*');
}
System.out.println(sb); // ************1111
}
}Reading with charAt(i) and writing with setCharAt(i, c) is faster than deleting and inserting a character, because nothing needs to shift. Prefer it when each output character corresponds to exactly one input character.
setLength: truncating, padding and reusing
setLength(n) forces the length to n.
- If
nis smaller than the current length, the extra characters are cut off. - If
nis larger, the new positions are filled with the null character'\u0000'. - A negative
nthrowsStringIndexOutOfBoundsException.
public class SetLengthDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.setLength(3);
System.out.println(sb); // Hel
sb.setLength(5);
System.out.println(sb.length()); // 5, the last two chars are '\0'
sb.setLength(0);
System.out.println(sb.length()); // 0
}
}Padding with '\0' is rarely what you want, so treat growth through setLength as a special case. The two common uses are shown below.
- Trimming a trailing separator. Loops that append
item + ", "leave a separator at the end. OnesetLengthcall removes it. - Emptying a builder for reuse.
sb.setLength(0)clears the contents and keeps the internal buffer, so a builder reused in a loop does not need to reallocate. Creating a fresh builder per iteration also works, and is often clearer.
Practical recipes
The following program collects three idioms that combine the methods above.
import java.util.List;
public class Recipes {
// Replace every occurrence of target, working by position.
static void replaceAll(StringBuilder sb, String target, String replacement) {
if (target.isEmpty()) {
return;
}
int from = 0;
int idx;
while ((idx = sb.indexOf(target, from)) >= 0) {
sb.replace(idx, idx + target.length(), replacement);
from = idx + replacement.length(); // skip past the new text
}
}
static boolean isPalindrome(String s) {
return new StringBuilder(s).reverse().toString().equals(s);
}
public static void main(String[] args) {
StringBuilder text = new StringBuilder("a-b-c");
replaceAll(text, "-", "--");
System.out.println(text); // a--b--c
StringBuilder joined = new StringBuilder();
for (String w : List.of("a", "b", "c")) {
joined.append(w).append(", ");
}
if (joined.length() > 0) {
joined.setLength(joined.length() - 2);
}
System.out.println(joined); // a, b, c
System.out.println(isPalindrome("level")); // true
System.out.println(isPalindrome("Java")); // false
}
}Two details in replaceAll prevent bugs:
- The search restarts at
idx + replacement.length(), not atidx. Otherwise, a replacement that contains the target (like"-"becoming"--") would be found again and the loop would never end. - The empty-target check stops
indexOf("", from)from matching at every position.
In isPalindrome, the comparison is done on String values. Do not write sb.reverse().equals(sb). StringBuilder does not override equals, so it compares object identity, not content. If you need to compare two builders, compare toString() results, or use compareTo (available since Java 11).
Reverse and surrogate pairs
Java stores text as UTF-16 char values. Characters outside the Basic Multilingual Plane, such as most emoji, take two char values called a surrogate pair. A naive reversal would swap the two halves and corrupt the character. StringBuilder.reverse() treats a valid surrogate pair as a single unit, so it stays intact:
public class SurrogateDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("a\uD83D\uDE00b"); // a, U+1F600, b
System.out.println(sb.length()); // 4 chars
System.out.println(sb.codePointCount(0, sb.length())); // 3 code points
sb.reverse();
System.out.println(sb.codePointAt(1) == 0x1F600); // true
}
}This protects against corrupting emoji, but it does not make reversal linguistically correct. A visible character made of several code points (for example a letter followed by a combining accent) is still split, and the pieces are reversed individually. For fully correct handling of user-visible characters you would need java.text.BreakIterator. That is beyond this chapter.
The same two-char fact affects indexes. length(), charAt, insert and delete all count char values, not visible characters. An emoji occupies two index positions, so deleting at the wrong index can cut a pair in half.
Common errors
- Forgetting that the builder is shared.
StringBuilder b = a;copies the reference, not the text. An edit throughbchanges whatashows. Passnew StringBuilder(a)ora.toString()when you need an independent copy. - Expecting a new object. Writing
sb.reverse();and then using an oldStringcopy gives stale text. Read the builder, or calltoString()after editing. - Calling
sb.replace('a', 'b'). No such method exists.replaceneeds two indexes and aString. - Using
Stringmethods on a builder.StringBuilderhas notrim,toUpperCaseorsplit. Convert withtoString(), apply the method, and build again if necessary. - Mixing up
deleteanddeleteCharAtends.delete(2, 3)removes one character, the one at index 2.delete(2, 2)removes nothing.
Exercise
Given StringBuilder sb = new StringBuilder("0123456789");, what does sb.delete(2, 5).insert(2, "-").replace(0, 1, "AB") leave in sb, and what is its length?
Show answer
delete(2, 5) removes "234", leaving "0156789". insert(2, "-") gives "01-56789". replace(0, 1, "AB") swaps "0" for "AB", so sb is "AB1-56789" with length 9.
Exercise
A loop appends each of the words "red", "green" and "blue" followed by a semicolon and a space. Write the single line that removes the trailing "; " from a builder sb, and say what happens if the loop ran zero times and you used the same line.
Show answer
sb.setLength(sb.length() - 2); removes the last two characters. If the loop never ran, the length is 0, so the call becomes setLength(-2) and throws StringIndexOutOfBoundsException. Guard it with if (sb.length() > 0).
Exercise
Which of these calls throws on StringBuilder sb = new StringBuilder("abc");: sb.insert(3, "x"), sb.delete(1, 50), sb.setCharAt(3, 'x'), sb.deleteCharAt(0)? Explain why for each.
Show answer
Only sb.setCharAt(3, 'x') throws. Its index must be less than the length (3), so index 3 is out of range. insert(3, "x") is allowed because an insert offset may equal the length. delete(1, 50) clamps the end to 3. deleteCharAt(0) is a valid index.