Java String lastIndexOf() 方法

String lastIndexOf() 方法的语法是以下两者之一:

string.lastIndexOf(int ch, int index)

或者

string.lastIndexOf(string str, int index)

lastIndexOf() 参数

要查找字符的最后出现索引,lastIndexOf() 接受这两个参数:

  • ch - 要查找最后一个索引的字符
  • index (可选) - 如果传递了 index,则从开始到该索引搜索 ch 字符

要查找字符串中指定子字符串的最后一个出现索引,lastIndexOf() 接受这两个参数:

  • str - 要查找最后一个索引的字符串
  • index (可选) - 如果传递了 index,则从开始到该索引搜索 str 字符串

lastIndexOf() 返回值

  • 返回指定字符/字符串最后一次出现的索引
  • 如果找不到指定的字符/字符串,则返回 -1。

示例 1:Java String lastIndexOf()

// Java String lastIndexOf() with only one parameter
class Main {
  public static void main(String[] args) {
    String str1 = "Learn Java";
    int result;

    // getting index of character 'J'
    result = str1.lastIndexOf('J');
    System.out.println(result); // 6

    // the last occurrence of 'a' is returned
    result = str1.lastIndexOf('a');
    System.out.println(result); // 9

    // character not in the string
    result = str1.lastIndexOf('j');
    System.out.println(result); // -1

    // getting the last occurrence of "ava"
    result = str1.lastIndexOf("ava");
    System.out.println(result); // 7

    // substring not in the string
    result = str1.lastIndexOf("java");
    System.out.println(result); // -1
  }
}

注意: 字符 'a' 在字符串 "Learn Java" 中出现多次。lastIndexOf() 方法返回 'a' 最后一次出现的索引(即 9)。


示例 2:lastIndexOf() 带有 fromIndex 参数

class Main {
  public static void main(String[] args) {
    String str1 = "Learn Java programming";
    int result;

    // search from index 0 to 4
    // searches the substring "Learn"
    result = str1.lastIndexOf('r', 4);
    System.out.println(result); // 3

    // search from index 0 to 12
    // searcheses the substring "Learn Java pr"
    result = str1.lastIndexOf('r', 12);
    System.out.println(result); // 12

    // string length is less than 100
    // searches the whole string
    result = str1.lastIndexOf('r', 70);
    System.out.println(result); // 15

    // searches the substring "Learn"
    result = str1.lastIndexOf("Java", 4);
    System.out.println(result); // -1
  }
}

注意事项

  • 字符串 "Learn Java programming"'r' 的最后一次出现是在索引 15。但是,str1.lastIndexOf('r', 4) 搜索子字符串 "Learn"'r'"Learn" 中的最后一个索引是 3。
  • str1.lastIndexOf('r', 12) 搜索子字符串 "Learn Java pr"'r'"Learn Java pr" 中的最后一个索引是 12。
  • str1.lastIndexOf("Java", 4) 搜索子字符串 "Learn"。由于 "Learn" 子字符串中没有 "Java",因此结果为 -1。

推荐阅读: Java String indexOf()

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战