Get last n characters from a String in Java
This post will discuss how to get the last n characters from a string in Java.
1. Using Apache Commons Lang
To get the rightmost n characters of a string, you can use the right() method offered by the StringUtils class from Apache Commons Lang. The advantage of using this method is that it doesn’t throw StringIndexOutOfBoundsException or NullPointerException when n characters are not available, or the string is null.
|
1 2 3 4 5 6 7 8 9 10 11 |
import org.apache.commons.lang3.StringUtils; public class Main { public static void main(String[] args) { String s = "ABCD"; int n = 2; System.out.println(StringUtils.right(s, n)); // CD } } |
2. Using String.substring() method
To remove the n characters from the end of a string, you can make a call to the substring() method with the last n indices excluded. Here’s a utility method demonstrating this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Main { public static String getLastN(String s, int n) { if (s == null || n > s.length()) { return s; } return s.substring(s.length() - n); } public static void main(String[] args) { String s = "ABCD"; int n = 2; System.out.println(getLastN(s, n)); // CD } } |
Here’s an alternative version that performs length check within the substring() method:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Main { public static String getLastN(String s, int n) { if (s == null) { return null; } return s.substring(Math.max(0, s.length() - n)); } public static void main(String[] args) { String s = "ABCD"; int n = 2; System.out.println(getLastN(s, n)); // CD } } |
That’s all about getting the last 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 :)