Java String lastIndexOf() 方法
示例
搜尋字串中 "planet" 的最後一次出現
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.lastIndexOf("planet"));
定義和用法
lastIndexOf()
方法返回指定字元(或字元序列)在字串中最後一次出現的位置。
提示:使用 indexOf 方法返回指定字元(或字元序列)在字串中首次出現的位置。
語法
以下之一
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)
public int lastIndexOf(int char)
public int lastIndexOf(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.lastIndexOf("e", 5));
}
}
❮ String Methods