Remove first n characters from a String in Java
This post will discuss how to remove the first n characters from a String in Java.
You cannot modify a string in Java since they are immutable. The only way to remove the first n characters from it is to create a new String object with the first n chars removed. There are several ways to do it:
1. Using Apache Commons library
A simple, concise, and elegant solution is to use the StringUtils class from Apache Commons Lang library whose removeStart() method removes a substring from the beginning of a source string, if present. You can use it as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import org.apache.commons.lang3.StringUtils; public class Main { public static String removefirstNchars(String str, int n) { if (str == null || str.length() < n) { return str; } String firstNchars = str.substring(0, n); return StringUtils.removeStart(str, firstNchars); } public static void main(String[] args) { String str = "Hello World"; int n = 6; System.out.println(removefirstNchars(str, n)); // World } } |
2. Using String#substring() method
If you don’t prefer the Apache Commons library, you can use the String#substring() method to get a substring starting from the specific position in the string till its end.
|
1 2 3 4 5 6 7 8 9 10 |
public class Main { public static void main(String[] args) { String str = "Hello World"; int n = 6; System.out.println(str.substring(n)); // World } } |
If the specified index is negative or larger than the string’s length, IndexOutOfBoundsException will be thrown. You can easily handle it by placing a length check before invoking the substring() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Main { public static String removefirstNchars(String str, int n) { if (str == null || str.length() < n) { return str; } return str.substring(n); } public static void main(String[] args) { String str = "Hello World"; int n = 6; System.out.println(removefirstNchars(str, n)); // World } } |
That’s all about removing the first n characters from a String in Java.
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 :)