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.

Comments 2

Leave a Reply

Your email address will not be published. Required fields are marked *