How do I get the last character of a string?

前端 未结 11 2182
遥遥无期
遥遥无期 2020-12-02 07:59

How do I get the last character of a string?

public class Main {
    public static void main(String[] args)  {
        String s = "test string";
            


        
相关标签:
11条回答
  • 2020-12-02 08:31
     public char lastChar(String s) {
         if (s == "" || s == null)
            return ' ';
        char lc = s.charAt(s.length() - 1);
        return lc;
    }
    
    0 讨论(0)
  • 2020-12-02 08:34
    public String lastChars(String a) {
    if(a.length()>=1{
    String str1 =a.substring(b.length()-1);
    }
    return str1;
    }
    
    0 讨论(0)
  • 2020-12-02 08:38

    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")) {
    
    0 讨论(0)
  • 2020-12-02 08:38
    public char LastChar(String a){
        return a.charAt(a.length() - 1);
    }
    
    0 讨论(0)
  • 2020-12-02 08:41

    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.

    0 讨论(0)
  • 2020-12-02 08:46

    Try this:

    if (s.charAt(0) == s.charAt(s.length() - 1))
    
    0 讨论(0)
提交回复
热议问题