You may also try the following code with exception handling. Here you have a method removeLast(String s, int n)
(it is actually an modified version of masud.m's answer). You have to provide the String
s and how many char
you want to remove from the last to this removeLast(String s, int n)
function. If the number of char
s have to remove from the last is greater than the given String
length then it throws a StringIndexOutOfBoundException
with a custom message -
public String removeLast(String s, int n) throws StringIndexOutOfBoundsException{
int strLength = s.length();
if(n>strLength){
throw new StringIndexOutOfBoundsException("Number of character to remove from end is greater than the length of the string");
}
else if(null!=s && !s.isEmpty()){
s = s.substring(0, s.length()-n);
}
return s;
}