1
0

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】startsWith・endsWith,メソッド(開始 / 終了の文字を判定する)

Last updated at Posted at 2020-12-12

Javaの startsWithメソッド

についてまとめました。

startsWid]thメソッドとは

要約すると「指定した文字列で文頭や文末が一致しているか、パターンマッチ判定するメソッド」です。

【説明】

◯◯Withメソッドは、文字列を指定し、その文字列で始まるどうかを判定するメソッドです。共通して返ってくる値はbool型で「true / false」を返します。

用途に応じた使い分けは以下です。

  • 前方一致の判定: startsWithメソッド
  • 後方一致の判定: endsWithメソッド

startsWithメソッドは、例えばIf文などに組み込んで電話番号を入力する箇所の数字が090や070で始まるか判定したりするのに使えます。

【書き方】

判定したい文字列をString型で指定するなど、基本的に書き方はおなじです。それぞれ書き方はこちら。

// startsWith 構文
文字列.startsWith(String 判定する文字列);
// サンプルコード
str.startsWith("Hello")

// endsWith の構文
文字列.endsWith(String 判定する文字列);
// サンプルコード
str.endsWith("bye")

startsWithの書き方2

startsWithメソッドには、引数offsetを指定した、別の書き方があります。形式は以下です。

// startsWith 構文2
文字列.startsWith(判定する文字列, 判定を開始する位置);

// サンプルコード
str.startsWith("Hello", 3)

メソッドチェイン

あるメソッドが戻すオブジェクトののメソッドをさらに呼び出すことを「メソッドチェイン」と呼びます。

以下のコードは「何文字目から何文字目の文字を調べるメソッド」と「指定した文字列は何から始まるかを判定するメソッド」の役割の違ったメソッドを組み合わせた例になります。

public class Main {

    public static void main(String[] args) {
        String str = "あいうえお";
        // 文字列の2〜4文字の、最初の文字は「い」か判定
        System.out.println(str.substring(1, 3).startsWith("い"));

    }

}
true

【まとめ】

JavaSilverの学習中当たり前のように出てきたのでポイントをおさらいすると

  • 前方一致の判定: startsWithメソッド
  • 後方一致の判定: endsWithメソッド
  • 判定結果はfalse と true
  • startsWithメソッドは判定開始位置を指定する書き方ができる

ということを抑えておく。

またメソッドチェーンを用いたややこしいことを聞かれてもいいように、わからなくなったらロジックを書き出す。

参考文献・記事

1
0
2

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?