Java字串最後

在Java程式設計中,字串(String)是最常用的資料型別之一。如果你想要取得字串的最後一個字元,你可以使用字串提供的charAt()方法。這個方法會返回字串中指定位置的字元。

以下是如何取得字串最後一個字元的範例:

public class StringLastCharExample {
    public static void main(String[] args) {
        String str = "Hello World!";
        char lastChar = str.charAt(str.length() - 1);
        System.out.println("The last character of the string is: " + lastChar);
    }
}

在上面的程式碼中,我們定義了一個字串str,然後使用charAt()方法來取得字串中索引位置為str.length() - 1的字元,這將返回字串的最後一個字元。

請注意,字串的索引從0開始,所以如果你想要取得最後一個字元,你需要使用字串長度減1來計算索引位置。

如果你想要取得字串的最後一個字元,並將其作為字串來使用,你可以這樣做:

public class StringLastCharExample {
    public static void main(String[] args) {
        String str = "Hello World!";
        String lastCharAsString = Character.toString(str.charAt(str.length() - 1));
        System.out.println("The last character of the string is: " + lastCharAsString);
    }
}

這個範例將最後一個字元轉換為字串,以便你可以對其進行操作或輸出。