Languages
[Edit]
EN

Java - remove last character from string

14 points
Created by:
Root-ssh
97550

1. Overview

In this post we will see how to remove last character from String in java.

All below examples except StringUtils.chop can be used to remove any number of characters from the end of the string.

Example:

String original = "123";
String expected = "12";

2. Remove last char with String.substring

Code example: 

public class RemoveCharExample1 {

    public static void main(String[] args) {
        String original = "123";
        String result = original.substring(0, original.length() - 1);

        System.out.println(original); // 123
        System.out.println(result);   // 12
    }
}

Output:

123
12

3. Remove last char with StringBuilder.delete

Code example: 

public class RemoveCharExample2 {

    public static void main(String[] args) {
        String original = "123";

        StringBuilder builder = new StringBuilder(original);
        builder.delete(builder.length() - 1, builder.length());

        String result = builder.toString();

        System.out.println(original); // 123
        System.out.println(result);   // 12
    }
}

Output:

123
12

4. Remove last char with Java 8 Optional

Code example: 

import java.util.Optional;

public class RemoveCharExample3 {

    public static void main(String[] args) {
        String original = "123";

        String result = Optional.ofNullable(original)
                .map(str -> str.substring(0, str.length() - 1))
                .orElse(original);

        System.out.println(original); // 123
        System.out.println(result);   // 12
    }
}

Output:

123
12

5. Remove last char with Apache Commons - StringUtils.chop

Code example:

import org.apache.commons.lang3.StringUtils;

public class RemoveCharExample4 {

    public static void main(String[] args) {
        String original = "123";
        String result = StringUtils.chop(original);

        System.out.println(original); // 123
        System.out.println(result);   // 12
    }
}

Output:

123
12

6. Remove last char with Apache Commons - StringUtils.substring()

Code example: 

import org.apache.commons.lang3.StringUtils;

public class RemoveCharExample5 {

    public static void main(String[] args) {
        String original = "123";
        String result = StringUtils.substring(original, 0, original.length() - 1);

        System.out.println(original); // 1234
        System.out.println(result);   // 12
    }
}

Output:

123
12

References

  1. String.substring - Java docs

Java - String (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join