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

文字列の先頭1文字を取得する方法は、2つあります。
charAt()
1つは、charAt()を使う方法です。
まず、文字列からcharAt()を呼び出します。
そして、charAt()の引数に0を指定します。
char first = text.charAt(0);
上記のcharAt()は、呼び出した文字列の先頭1文字をchar型として取得します。
使用例
public class Main {
public static void main(String[] args) throws Exception {
String text = "Hello,World";
char first = text.charAt(0);
System.out.println(first);
}
}
出力:
H
substring()
もう1つは、substring()を使う方法です。
まず、文字列からsubstring()を呼び出します。
そして、substring()の第1引数に0、第2引数に1を指定します。
String first = text.substring(0, 1);
上記のsubstring()は、呼び出した文字列の先頭1文字をString型として取得します。
使用例
public class Main {
public static void main(String[] args) throws Exception {
String text = "Hello,World";
String first = text.substring(0, 1);
System.out.println(first);
}
}
出力:
H
まとめ
文字列(string)の最初の文字する方法は、次の2つです。
- charAt()を使う方法
char first = text.charAt(0);
int result = rnd.nextInt();
- substring()を使う方法
String first = text.substring(0, 1);
コメント