Stringをcharacterに変換


String型をcharacterに変換するために2つのメソッドがあります。
最初のsampleは1つのStringの全ての文字をcharacterに変換、
2つ目のサンプルは1つのStringの中で、指定された1つの文字をcharacterに変換しています。

class  ExamStoChar1  {
    public  static  void  main(String  args[])  {
        String  s   = "abcd";
        char  ch[]  = s.toCharArray();
        for (int  idx  = 0;  idx < s.length();  idx++)  {
            System.out.println(ch[idx]);
        }
    }
}
 
class  ExamStoChar2  {
    public  static  void  main(String  args[])  {
        String  s   = "abcd";
        char  ch    = s.charAt(3);
        System.out.println(ch);
    }
}


実行結果
ExamStoChar1 の場合
a
b
c
d
とコンソールに表示されます。

ExamStoChar2の場合
d
とコンソールに表示されます。


charAt() method
charAt()メソッドの引数は、何番目の文字を変換するかを指定しており、指定した1文字だけが変換されます。
もちろんindexは配列のindexと同じように0から始まります。
Stringと整数に関する変換はこちら