How do I get the last character of a string?
public class Main
{
public static void main(String[] args)
{
String s = "test string";
//char lastChar = ???
}
}
How do I get the last character of a string?
public class Main
{
public static void main(String[] args)
{
String s = "test string";
//char lastChar = ???
}
}
Here is a method using
String.charAt()
:The resulting output is
last char = a
.The other answers are very complete, and you should definitely use them if you're trying to find the last character of a string. But if you're just trying to use a conditional (e.g. is the last character 'g'), you could also do the following:
or, strings
Simple solution is:
Using a character array (watch out for the nasty empty String or null String argument!)
Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.
Yet another approach (more for instruction than actual use) is this one:
Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)