Is there any quick way to get the last two characters in a string?
JavaJava Problem Overview
Wondering how to substring the last two characters quickly in Java?
Java Solutions
Solution 1 - Java
The existing answers will fail if the string is empty or only has one character. Options:
String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;
or
String substring = str.substring(Math.max(str.length() - 2, 0));
That's assuming that str
is non-null, and that if there are fewer than 2 characters, you just want the original string.
Solution 2 - Java
theString.substring(theString.length() - 2)
Solution 3 - Java
String value = "somestring";
String lastTwo = null;
if (value != null && value.length() >= 2) {
lastTwo = value.substring(value.length() - 2);
}
Solution 4 - Java
Use substring method like this::
str.substring(str.length()-2);
Solution 5 - Java
In my case, I wanted the opposite. I wanted to strip off the last 2 characters in my string. This was pretty simple:
String myString = someString.substring(0, someString.length() - 2);