Languages
[Edit]
EN

Java - remove last 2 characters from string

1 points
Created by:
Root-ssh
175400

1. Overview

In this post, we will see how to remove the last 2 characters from any String in java.

In the below examples, we can change the number of characters we want to remove.

We can remove the last n characters. For example, we can remove the last character, last 3, 4, 5 x characters. We just need to ensure that the string is long enough. 

Example:

String original = "1234";
String expected = "12";

2. Remove char with String.substring()

Code example: 

public class RemoveCharsExample1 {

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

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

Output:

1234
12

3. Remove char with StringBuilder.delete()

Code example: 

public class RemoveCharsExample2 {

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

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

        String result = builder.toString();

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

Output:

1234
12

4. Remove char with Java 8 Optional

Code example: 

import java.util.Optional;

public class RemoveCharsExample3 {

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

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

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

Output:

1234
12

5. Remove char with Apache Commons - StringUtils.substring()

Code example: 

import org.apache.commons.lang3.StringUtils;

public class RemoveCharsExample4 {

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

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

Output:

1234
12

Merged questions

  1. Java remove last n characters from string
  2. How to remove last 2 chars in java?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - remove last 2 characters from string

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