Remove a suffix from a String in Java
In this quick article, we’ll explore how to remove a suffix from a string in Java.
1. Using String.substring() method
The recommended approach is to make use of the substring() method of the String class, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Main { public static String removeSuffix(final String s, final String suffix) { if (s != null && suffix != null && s.endsWith(suffix)) { return s.substring(0, s.length() - suffix.length()); } return s; } public static void main(String[] args) { String s = "Java9"; System.out.println(removeSuffix(s, "9")); } } |
Output:
Java
2. Using String.split() method
Another plausible way is to split the given string around the given suffix using the split() method of the String class and return the first value of the string array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Main { public static String removeSuffix(final String s, final String suffix) { if (s != null && s.endsWith(suffix)) { return s.split(suffix)[0]; } return s; } public static void main(String[] args) { String s = "Java9"; System.out.println(removeSuffix(s, "9")); } } |
Output:
Java
3. Using Apache Commons Lang
You might also want to look at the StringUtils class of the Apache Commons Lang library, which provides the removeStart() utility method that does the job.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import org.apache.commons.lang3.StringUtils; class Main { public static String removeSuffix(final String s, final String suffix) { return StringUtils.removeEnd(s, suffix); } public static void main(String[] args) { String s = "Java9"; System.out.println(removeSuffix(s, "9")); } } |
That’s all about removing a suffix from a Java String.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)