Java String lastIndexOf() 方法

来源:这里教程网 时间:2026-02-16 11:51:01 作者:

前言

定义和用法lastIndexOf() 方法返回字符串中指定字符最后一次出现的位置。提示:使用 indexOf() 方法返回字符串中指定字符第一次出现的位置。实例


定义和用法

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

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


实例

例子 1

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

String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.lastIndexOf("planet"));

运行实例 »

点击 "运行实例" 按钮查看在线实例

例子 2

查找字符串中最后一次出现的 "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));
  }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例


语法

有 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 String 值,表示要搜索的字符串。
fromIndex int 值,表示开始搜索的索引位置。如果省略,则默认值为字符串的长度。
char int 值,表示单个字符,例如 ,或 Unicode 值。

技术细节

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

相关推荐