Is there any quick way to get the last two characters in a string?
theString.substring(theString.length() - 2)
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.
String value = "somestring";
String lastTwo = null;
if (value != null && value.length() >= 2) {
lastTwo = value.substring(value.length() - 2);
}