Remove a prefix from a String in Java
This post will discuss how to remove a prefix from a string in Java.
1. Using String.substring() method
The standard solution 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 removePrefix(String s, String prefix) { if (s != null && prefix != null && s.startsWith(prefix)) { return s.substring(prefix.length()); } return s; } public static void main(String[] args) { String s = "supernatural"; System.out.println(removePrefix(s, "super")); } } |
Output:
natural
2. Using String.split() method
Another plausible way is to split the given string around the given prefix using the split() method of the String class and return the second string value of the array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Main { public static String removePrefix(String s, String prefix) { if (s != null && s.startsWith(prefix)) { return s.split(prefix, 2)[1]; } return s; } public static void main(String[] args) { String s = "supernatural"; System.out.println(removePrefix(s, "super")); } } |
Output:
natural
3. Using Apache Commons Lang
We can also use the Apache Commons Lang library, which has the removeStart() utility method in the StringUtils class, which does the job and handles NullPointerException.
|
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 removePrefix(String s, String prefix) { return StringUtils.removeStart(s, prefix); } public static void main(String[] args) { String s = "supernatural"; System.out.println(removePrefix(s, "super")); } } |
That’s all about removing a prefix 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 :)