Languages
[Edit]
EN

Java - remove suffix from string

0 points
Created by:
maxsior322
227

In this article, we would like to show you how to remove suffix from string in Java.

Quick solution:

String text = "ABCD";

// replace the last two characters with empty string
String result1 = text.replaceAll(".{0,2}$", "");

// remove the last two characters
String result2 = text.substring(0, text.length() - 2);

System.out.println(result1);  // AB
System.out.println(result2);  // AB

 

Practical examples

1. String replaceAll() with regex

In this example, we use replaceAll() method with regex to replace the last two letters (CD suffix) with an empty string.

public class Example {

    public static void main(String[] args) {
        String text = "ABCD";

        // replace the last two characters with empty string
        String result = text.replaceAll(".{0,2}$", "");

        System.out.println(result);  // AB
    }
}

2. String substring()

In this example, we use substring() method to remove the last two letters (CD suffix) from the text.

public class Example {

    public static void main(String[] args) {
        String text = "ABCD";

        // remove the last two characters
        String result = text.substring(0, text.length() - 2);

        System.out.println(result);  // AB
    }
}

Java - String (popular problems)

Java - remove suffix 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