insert and delete
- Java course
- Beginner
- Lesson 90/116
- 4 min
Learn to edit text with insert and delete.
insert and delete
With insert you add content at a specific index, and with delete you remove a range. These methods modify the StringBuilder in place.
StringBuilder sb = new StringBuilder("Merhaba");
sb.insert(0, "Selam ");
// "Selam Merhaba"
sb.delete(0, 6);
// "Merhaba"insert shifts the second parameter to the first index; the rest moves right. delete(start, end) removes the range with start inclusive and end exclusive.
Prepend with insert
The most common insert example is prepending content. insert(0, ...) does that.
StringBuilder sb = new StringBuilder("world");
sb.insert(0, "Hello ");
// "Hello world"Here insert(0, ...) puts the new content at the very front; the existing "world" shifts right. This is much more efficient than String when you need to prepend repeatedly.
Practice Insert a heading and clean up
Start a StringBuilder with "Monthly Report". Use insert(0, "--- ") to add dashes at the front. Then use delete(0, 4) to remove those dashes. Print the result with toString.
Starter code
public class Main {
public static void main(String[] args) {
// Start the StringBuilder with "Monthly Report"
// Prepend "--- "
// Delete the first 4 characters
// Print the result with toString
}
}Sample solution
StringBuilder sb = new StringBuilder("Monthly Report");
sb.insert(0, "--- ");
sb.delete(0, 4);
System.out.println(sb.toString());Expected output
Monthly Report
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does sb.delete(1, 3) do?
- Removes indices 1 and 2
- Removes indices 1 and 3
- Removes from index 1 to 3 (3 inclusive) Correct answer
- Removes the third character
Explanation: delete(start, end) is start inclusive, end exclusive.
2 Match call to result
| Term | Meaning |
|---|---|
insert(0, "X") |
Prepends X |
insert(3, "X") |
Inserts X at index 3 |
delete(0, 2) |
Removes the first two chars |
delete(1, 1) |
Removes nothing |
3 Fill in the blank: prepend
StringBuilder sb = new StringBuilder("world");
sb.____(0, "Hello ");
StringBuilder sb = new StringBuilder("world");
sb.insert(0, "Hello ");
Explanation: insert(0, "Hello ") prepends.