StringBuilder.insert()
Inserts a value at the given position of a StringBuilder.
Available since: Java 5
Syntax
public StringBuilder insert(int offset, Object obj)Parameters
| Parameter | Type | Description |
|---|---|---|
| offset | int | The index to insert before: 0 for the start, length() for the end. |
| obj | Object, String, int, char… | What to insert. |
Return value
StringBuilderThe same StringBuilder.
Examples
Inserting at the start and in the middle:
void main() {
var sb = new StringBuilder("world");
sb.insert(0, "Hello ");
sb.insert(5, ",");
IO.println(sb);
}Output:
Hello, worldThousands separators by hand — inserting from right to left:
void main() {
var sb = new StringBuilder("1234567");
for (int i = sb.length() - 3; i > 0; i -= 3) {
sb.insert(i, ' ');
}
IO.println(sb);
}Output:
1 234 567Notes
An index outside 0..length() throws StringIndexOutOfBoundsException. Inserting at the start shifts all characters, so in a long loop it is cheaper to append and call reverse() at the end.
See also
- StringBuilder.append() — Adds a value to the end of a StringBuilder.
- StringBuilder.deleteCharAt() — Removes one character at an index. For a range there is delete(start, end).
- StringBuilder — A mutable string: useful when text is built piece by piece, especially in a loop.
In the tutorial
- StringBuilder — StringBuilder in Java: a mutable string, append, insert, reverse, deleteCharAt, call chains and building a string in a loop.