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:
xxxxxxxxxx
1
String text = "ABCD";
2
3
// replace the last two characters with empty string
4
String result1 = text.replaceAll(".{0,2}$", "");
5
6
// remove the last two characters
7
String result2 = text.substring(0, text.length() - 2);
8
9
System.out.println(result1); // AB
10
System.out.println(result2); // AB
In this example, we use replaceAll()
method with regex to replace the last two letters (CD
suffix) with an empty string.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
6
// replace the last two characters with empty string
7
String result = text.replaceAll(".{0,2}$", "");
8
9
System.out.println(result); // AB
10
}
11
}
In this example, we use substring()
method to remove the last two letters (CD
suffix) from the text
.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
6
// remove the last two characters
7
String result = text.substring(0, text.length() - 2);
8
9
System.out.println(result); // AB
10
}
11
}