Sub topic 4
Inserting, Deleting, Replacing and Reversing
This chapter assumes that you know Java variables, loops, methods, and the String class. You should also know that String objects are immutable. StringBuilder is mutable, so its existing character sequence can change without creating a new builder for every edit.
Indexes and End Positions
A StringBuilder uses zero-based indexes. The first character is at index 0. Most editing methods use a start index and an end index. The end index is exclusive, so it identifies the position just after the final character to change.
For example, in "Hello":
| Expression | Characters or position |
|---|---|
| `substring(0, 2)` | `He` |
| `delete(1, 4)` | Deletes `ell` |
| `replace(0, 5, "Hi")` | Replaces the entire string |
The valid character indexes run from 0 through length() - 1. An insertion can use length() as its index because inserting at that position appends text.
Inserting and Replacing Text
insert adds text at a position and keeps the original characters. The text after that position moves to the right.
replace removes the range from start through end - 1, then inserts the replacement text. The replacement can have a different length from the removed range.
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.replace(5, 8, ",");
System.out.println(sb); // Howdy, World
}
}After the first operation, the original comma moves from index 5 to index 8. This matters when you perform several edits. An earlier insertion or deletion can change the indexes of characters that later operations need to access.
Deleting and Reversing
delete(start, end) removes a range. deleteCharAt(index) removes exactly one character.
reverse() reverses the entire sequence in place. It returns the same builder, so it can be chained with other operations, although separate statements are often easier to read.
setCharAt(index, character) changes one character without changing the builder's length. setLength(newLength) changes the length directly:
- Increasing the length adds null characters, written as
\u0000. - Decreasing the length discards characters from the end.
public class MoreEdits {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("abcdef");
sb.setCharAt(1, 'X');
System.out.println(sb); // aXcdef
sb.deleteCharAt(3);
System.out.println(sb); // aXcef
sb.setLength(4);
System.out.println(sb); // aXce
sb.reverse();
System.out.println(sb); // ecXa
}
}Do not call setLength with a negative value or an index outside the valid range. These errors produce IndexOutOfBoundsException or StringIndexOutOfBoundsException.
A Worked Editing Sequence
Consider this sequence:
StringBuilder word = new StringBuilder("Java");
word.insert(4, " code"); // Java code
word.replace(0, 4, "Kotlin"); // Kotlin code
word.delete(6, 11); // Kotlin
word.reverse(); // niltoK
System.out.println(word);The indexes in delete(6, 11) refer to the current value, "Kotlin code", not the original value "Java". Always inspect the current sequence when calculating indexes.
A common safe approach is to perform edits from right to left when several fixed positions refer to the original text. Changes near the end then do not shift the indexes of earlier changes.
Character-Level Details
Java strings and builders index UTF-16 code units, not always user-perceived characters. Most basic Latin characters occupy one code unit. Some symbols, including many emoji, occupy two. reverse() handles surrogate pairs so that many supplementary characters remain valid, but it does not understand every visual grapheme, such as a letter combined with a separate accent mark.
For ordinary identifiers, commands, and formatted text, the basic index rules are usually sufficient. For user-facing international text, test edits with the languages and symbols your application supports.
Exercise
What does this code print, and why is the end index in delete exclusive? StringBuilder b = new StringBuilder("abcdef"); b.delete(1, 4); System.out.println(b);
Show answer
It prints aef. The method removes indexes 1, 2, and 3 (b, c, and d) but not index 4 (e).