どうも、ちょげ(@chogetarou)です。
charAt()で文字列(string)の末尾の文字を取得する方法を紹介します。
方法

charAt()で文字列(string)の最後の文字を取得するには、length()を使います。
まず、文字列からcharAt()を呼び出します。
そして、charAt()の引数に、文字列から呼び出したlength()の値を「−1」した値を指定します。
char last = text.charAt(text.length() - 1);
上記のcharAt()は、呼び出した文字列の末尾の文字をchar型として取得します。
使用例
public class Main {
public static void main(String[] args) throws Exception {
String text = "Hello,World";
char last = text.charAt(text.length() - 1);
System.out.println(last);
}
}
出力:
d
コメント