Java String lastIndexOf() 方法

实例

在字符串中搜索最后出现的 "planet":

  1. public class Main {
  2. public static void main(String[] args) {
  3. String myStr = "Hello planet earth, you are a great planet.";
  4. System.out.println(myStr.lastIndexOf("planet"));
  5. }
  6. }

定义与用法

lastIndexOf() 方法返回指定字符在字符串中最后一次出现的位置。

提示:使用 indexOf 方法返回字符串中指定字符第一次出现的位置。


语法

有 4 个 lastIndexOf() 方法:

  1. public int lastIndexOf(String str)
  2. public int lastIndexOf(String str, int fromIndex)
  3. public int lastIndexOf(int char)
  4. public int lastIndexOf(int char, int fromIndex)

参数值

参数描述
str字符串值,表示要搜索的字符串
fromIndex一个 int 值,表示开始搜索的索引位置
char表示单个字符的 int 值,例如 'a' 或 Unicode 值

技术细节

返回:一个 int 值, 表示字符串中第一次出现的字符的索引,如果从未出现,则为 -1

更多实例

实例

查找字符串中最后一个出现的字母 "e",从位置 5 开始搜索:

  1. public class Main {
  2. public static void main(String[] args) {
  3. String myStr = "Hello planet earth, you are a great planet.";
  4. System.out.println(myStr.lastIndexOf("e", 5));
  5. }
  6. }

分类导航