Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Wondering how to substring the last two characters quickly in Java?

like image 335
user705414 Avatar asked Jan 07 '12 09:01

user705414


People also ask

How do you find the last two characters of a string?

To get the last two characters of a string, call the slice() method, passing it -2 as a parameter. The slice method will return a new string containing the last two characters of the original string. Copied! The parameter we passed to the String.

How do you get the last few characters of a string?

To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.

How do I get the last 3 characters of a string?

Getting the last 3 characters To access the last 3 characters of a string, we can use the built-in Substring() method in C#. In the above example, we have passed s. Length-3 as an argument to the Substring() method.

How do I get the last two characters of a string in Python?

Use slice notation [length-2:] to Get the last two characters of string Python. For it, you have to get the length of string and minus 2 char.


2 Answers

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.

like image 129
Jon Skeet Avatar answered Oct 13 '22 19:10

Jon Skeet


theString.substring(theString.length() - 2) 
like image 27
Per Kastman Avatar answered Oct 13 '22 18:10

Per Kastman