Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

Hello

Only 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, c

In 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,3

Even 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 0

Check !text.isEmpty() before removing.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.