Remove last n characters from a String in Java
This post will discuss how to remove the last n characters from the end of a string in Java.
Since strings are immutable in Java, their length is fixed. That means we cannot make any change to the String instance. The only feasible solution is to create a new String object with the last n characters removed from the end of a string:
1. Using String.substring() method
The recommended approach is to use the substring() method provided by the String class. The idea is to take a substring from the beginning of the string and consider all the characters in it except the last n characters.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Main { public static String removeLastNchars(String str, int n) { return str.substring(0, str.length() - n); } public static void main(String[] args) { String str = "HelloWorld.java"; int n = 5; System.out.println(removeLastNchars(str, n)); // HelloWorld } } |
We should always ensure that a string is properly bounded, otherwise StringIndexOutOfBoundsException might be thrown. Here’s an exception-safe implementation:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Main { public static String removeLastNchars(String str, int n) { if (str == null || str.length() < n) { return str; } return str.substring(0, str.length() - n); } public static void main(String[] args) { String str = "HelloWorld.java"; int n = 5; System.out.println(removeLastNchars(str, n)); // HelloWorld } } |
2. Using StringUtils.removeEnd() method
We can also achieve this using the removeEnd method from the StringUtils class provided by the Apache Commons library. It removes a substring only if it is at the end of a source string, otherwise, it returns the source string. This is demonstrated below:
|
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 removeLastNchars(String str, int n) { if (str == null || str.length() < n) { return str; } String lastNChars = str.substring(str.length() - n); return StringUtils.removeEnd(str, lastNChars); } public static void main(String[] args) { String str = "Hello.java"; int n = 5; System.out.println(removeLastNchars(str, n)); // HelloWorld } } |
That’s all about removing the last n characters from the end of 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 :)