How do I get the last character of a string?
public class Main {
public static void main(String[] args) {
String s = "test string";
public char lastChar(String s) {
if (s == "" || s == null)
return ' ';
char lc = s.charAt(s.length() - 1);
return lc;
}
public String lastChars(String a) {
if(a.length()>=1{
String str1 =a.substring(b.length()-1);
}
return str1;
}
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:
if (str.endsWith("g")) {
or, strings
if (str.endsWith("bar")) {
public char LastChar(String a){
return a.charAt(a.length() - 1);
}
Here is a method using String.charAt()
:
String str = "India";
System.out.println("last char = " + str.charAt(str.length() - 1));
The resulting output is last char = a
.
Try this:
if (s.charAt(0) == s.charAt(s.length() - 1))