Course contentsShow
← Java
Lesson 2190 of 2,87043. String Handling in DepthFree lesson

Modifying Content: delete, deleteCharAt, and replace

Removing and replacing portions of the mutable string using index-based modification methods.

Modifying Content: delete, deleteCharAt, and replace

What you'll learn: How to remove and replace portions of text within a StringBuilder using index-based modification methods.

Why Modify Instead of Recreate?

Unlike immutable String objects, StringBuilder allows you to surgically edit specific portions of your text in place. Think of it like using a word processor's delete and replace functions rather than retyping entire paragraphs.

The Three Modification Methods

delete(int start, int end)

Removes characters from index start (inclusive) to end (exclusive). The method shifts remaining characters left to fill the gap.

StringBuilder sb = new StringBuilder("Hello World");
sb.delete(5, 11);  // Removes " World"
System.out.println(sb);  // Output: Hello

deleteCharAt(int index)

Removes a single character at the specified index. This is essentially delete(index, index + 1) but more readable for single-character removal.

StringBuilder sb = new StringBuilder("Java!");
sb.deleteCharAt(4);  // Removes the '!'
System.out.println(sb);  // Output: Java

replace(int start, int end, String str)

Replaces characters from start (inclusive) to end (exclusive) with the provided string. The replacement string can be any length—shorter, longer, or the same.

StringBuilder sb = new StringBuilder("I like cats");
sb.replace(7, 11, "dogs");  // Replaces "cats" with "dogs"
System.out.println(sb);  // Output: I like dogs

Index Boundaries Matter

All three methods use zero-based indexing. Using invalid indices (negative or beyond length) throws StringIndexOutOfBoundsException. Always verify your boundaries when working with dynamic content.

Key Takeaway: delete(), deleteCharAt(), and replace() enable precise, in-place editing of StringBuilder content, avoiding the overhead of creating new objects—essential for efficient string manipulation in loops or complex transformations.