Is there any quick way to get the last two characters in a string?

Java

Java 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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser705414View Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaPer KastmanView Answer on Stackoverflow
Solution 3 - Javaradu florescuView Answer on Stackoverflow
Solution 4 - JavaanubhavaView Answer on Stackoverflow
Solution 5 - JavaWill BuffingtonView Answer on Stackoverflow