6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】charAtメソッド(n番目の文字を抜き出す)

Posted at

JavaのcharAtメソッド

についてまとめました。

charAtメソッドとは

一言でいうと「文字列から指定位置の1文字を取得する」メソッドです。

【説明】

charAtメソッドは、文字の位置を指定することで該当の1文字を取得することができます。

書き方は以下です。

//chrAt
変数名.charAt()
  • 数字は、左から0でスタートする
  • 一番最後の文字の位置は文字列.length() – 1

【実際に書いてみる】

ひだりから数えて0スタートなので、「あいうえお」だと1を指定すると実質二番目の文字である「い」を取得してきます。

public class Main {

    public static void main(String[] args) {
        String str = "あいうえお";
        System.out.println(str.charAt(1));
    }

}

範囲外を選択すると?(結論: 例外発生

範囲外を選択すると例外が発生します。

例えば、文字列が5文字なのに対し、6番目を取得する「5」を指定した場合はjava.lang.StringIndexOutOfBoundsException

という例外がスローされます。

【まとめ】

抑えるポイントは以下です。

  • 範囲外を指定すると例外発生
  • 左から0スタート

参考文献・記事

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?