EN
Java - remove suffix from string
0
points
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
}
}