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】indexOfメソッド (指定した文字列が最初に出現する位置を返す)

Posted at

JavaのindexOfメソッド

についてまとめました。

indexOfメソッド とは?

要約すると、「ある文字列の中で、指定した文字列が最初に出現する位置を返す」というStringメソッドの1つです。

【特徴 / メリット】

引数の型と数により、以下の4通りの使い方があります。

文字列(String)型で検索する用法1

public int indexOf(文字列型変数名)
public class Main {
    public static void main(String[] args) {
        String s = "あいうえおかきくけこあいうえおかきくけこ";
        int n = s.indexOf("かきくけこ");
        System.out.println(n);
    }
}
5

文字列(String)型で検索する用法2

public int indexOf(文字列型変数名, 検索位置数)
public class Main {
    public static void main(String[] args) {
        String s = "あいうえおかきくけこあいうえおかきくけこ";
        int n = s.indexOf("かきくけこ", 8);
        System.out.println(n);
    }
}
15

文字(char)型で検索する用法1

public int indexOf(文字型変数名)
public class Main {
    public static void main(String[] args) {
        String s = "あいうえおかきくけこあいうえおかきくけこ";
        int n = s.indexOf("き");
        System.out.println(n);
    }
}
6

文字(char)型で検索する用法2

public int indexOf(文字型変数名, 検索位置数)
public class Main {
    public static void main(String[] args) {
        String s = "あいうえおかきくけこあいうえおかきくけこ";
        int n = s.indexOf("き", 7);
        System.out.println(n);
    }
}
16

出現しない文字・文字列を指定すると?(結論:-1)

存在しない文字を指定すると「-1」が返ってきます。

public class Main {
    public static void main(String[] args) {
        String s = "あいうえおかきくけこあいうえおかきくけこ";
        int n = s.indexOf("らりるれろ");//存在しない文字列を指定
        System.out.println(n);
    }
}
-1

【まとめ】

上記の4パターンの挙動と、「存在しない文字を指定すると「-1」が返る」ということを覚えておきましょう。

参考文献・記事

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