Wondering how to substring the last two characters quickly in Java?
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.
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.
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.
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.
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.
theString.substring(theString.length() - 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With