How to remove the last character of a string
Short answer
Take the substring without the last character:
void main() {
String text = "Hello!";
IO.println(text.substring(0, text.length() - 1));
}Output:
HelloOnly if it is the right character
More often you need to remove a specific tail — for example, an extra comma:
void main() {
String list = "a, b, c, ";
String trimmed = list.strip();
if (trimmed.endsWith(",")) {
trimmed = trimmed.substring(0, trimmed.length() - 1);
}
IO.println(trimmed);
}Output:
a, b, cIn a StringBuilder
If the string is built in a StringBuilder, remove the character right there:
void main() {
var builder = new StringBuilder();
for (int i = 1; i <= 3; i++) {
builder.append(i).append(",");
}
builder.deleteCharAt(builder.length() - 1);
IO.println(builder);
}Output:
1,2,3Even better is not to add the extra separator at all — that is what String.join() and StringJoiner are for.
Common mistake
Running the code on an empty string — length() - 1 gives -1:
void main() {
String text = "";
IO.println(text.substring(0, text.length() - 1));
}Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [0, -1) out of bounds for length 0Check !text.isEmpty() before removing.
Functions used in this recipe
- String.substring() — Returns the part of a string between two indexes.
- String.length() — Returns the number of characters in a string.
- StringBuilder.deleteCharAt() — Removes one character at an index. For a range there is delete(start, end).
- String.endsWith() — Checks whether a string ends with the given suffix.