Java String lastIndexOf() 方法
实例
在字符串中搜索最后出现的 "planet":
public class Main {public static void main(String[] args) {String myStr = "Hello planet earth, you are a great planet.";System.out.println(myStr.lastIndexOf("planet"));}}
定义与用法
lastIndexOf() 方法返回指定字符在字符串中最后一次出现的位置。
提示:使用 indexOf 方法返回字符串中指定字符第一次出现的位置。
语法
有 4 个 lastIndexOf() 方法:
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 | 字符串值,表示要搜索的字符串 |
| 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));}}