Java String indexOf() 方法
示例
搜尋字串中第一次出現的“planet”
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.indexOf("planet"));
定義和用法
indexOf() 方法返回指定字元在字串中第一次出現的位置。
提示: 使用 lastIndexOf 方法返回指定字元在字串中**最後**一次出現的位置。
語法
以下之一
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
public int indexOf(int char)
public int indexOf(int char, int fromIndex)
引數值
| 引數 | 描述 |
|---|---|
| str | 一個 String 值,表示要搜尋的字串 |
| fromIndex | 一個 int 值,表示開始搜尋的索引位置 |
| char | 一個 int 值,表示單個字元,例如 'A',或 Unicode 值 |
技術詳情
| 返回 | 一個 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));
}
}
❮ String Methods