How do I get the last character of a string?

2019-01-13 00:03发布

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 = ???
    }   
}

10条回答
Ridiculous、
2楼-- · 2019-01-13 00:04
 public char lastChar(String s) {
     if (s == "" || s == null)
        return ' ';
    char lc = s.charAt(s.length() - 1);
    return lc;
}
查看更多
趁早两清
3楼-- · 2019-01-13 00:08
public String lastChars(String a) {
if(a.length()>=1{
String str1 =a.substring(b.length()-1);
}
return str1;
}
查看更多
地球回转人心会变
4楼-- · 2019-01-13 00:14

The other answers contain a lot of needless text and code. Here are two ways to get the last character of a String:

char

char lastChar = myString.charAt(myString.length() - 1);

String

String lastChar = myString.substring(myString.length() - 1);
查看更多
5楼-- · 2019-01-13 00:17
String aString = "This will return the letter t";
System.out.println(aString.charAt(aString.length() - 1));

Output should be:

t

Happy coding!

查看更多
可以哭但决不认输i
6楼-- · 2019-01-13 00:19

Try this:

if (s.charAt(0) == s.charAt(s.length() - 1))
查看更多
你好瞎i
7楼-- · 2019-01-13 00:21

The code:

public class Test {
    public static void main(String args[]) {
        String string = args[0];
        System.out.println("last character: " +
                           string.substring(string.length() - 1)); 
    }
}

The output:

last character: f
查看更多
登录 后发表回答