Extract substring from end of a Java String
Today I’ll show you how to extract last few characters (a substring) from a string in Java.
Here is the code to do this.
public class SubStringEx{ /** Method to get the substring of length n from the end of a string. @param inputString - String from which substring to be extracted. @param subStringLength- int Desired length of the substring. @return lastCharacters- String @author Zaheer Paracha */ public String getLastnCharacters(String inputString, int subStringLength){ int length = inputString.length(); if(length <= subStringLength){ return inputString; } int startIndex = length-subStringLength; return inputString.substring(startIndex); } }
Let’s say you want to get the last four digits of a Social Security number. Here is how you will do this by calling the method declared above.
public static void main(String args[]){ String ssn ="123456789"; SubStringEx subEx = new SubStringEx(); String last4Digits = subEx.getLastnCharacters(ssn,4); System.out.println("Last 4 digits are " + last4Digits); //will print 6789 }
This method is useful in scenarios where you don’t know the length of a string. For example, a variable that holds credit card number may have a variable length. If you want to extract the last four digits of the credit card this method will come in handy.
Enjoy.
Grant
March 12, 2011 @ 3:48 pm
Nice code…it was exactly what I was looking for. I am using it to display a new member account information in a JInternalFrame. It works great and saved me the time of having to start from scratch.
Thanks!
Pakzap
February 13, 2013 @ 7:58 am
Excellent piece of code, It worked!
Thank you.
Vinod
February 1, 2018 @ 4:15 am
Nice one