Languages
[Edit]
EN

Java - remove last 2 characters from string

1 points
Created by:
Root-ssh
6266

1. Overview

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

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

We can remove last n characters. For example we can remove 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?

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍