Java文字列indexOf()メソッド
例
「planet」の最初の出現を文字列で検索します。
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.indexOf("planet"));
定義と使用法
このindexOf()
メソッドは、文字列内で最初に出現する文字の位置を返します。
ヒント:lastIndexOfメソッドを使用して、文字列内で最後に出現する文字の位置を返します。
構文
4つのindexOf()メソッドがあります。
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
public int indexOf(int char)
public int indexOf(int char, int fromIndex)
パラメータ値
Parameter | Description |
---|---|
str | A String value, representing the string
to search for |
fromIndex | An int value, representing the index position to start the search from |
char | An int value, representing a single
character, e.g 'A', or a Unicode value |
技術的な詳細
戻り値: | 文字列内で最初に出現するint 文字のインデックスを表す値、または出現しない場合は-1 |
---|
その他の例
例
文字列内の文字「e」の最初の出現箇所を検索し、位置5から検索を開始します。
public class Main {
public static void main(String[] args) {
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.indexOf("e", 5));
}
}
❮文字列メソッド