Java lastIndexOf方法详解

2025年01月20日 Java lastIndexOf方法详解 极客笔记

Java lastIndexOf方法详解

在Java中,String类提供了许多用于处理字符串的方法,其中包括lastIndexOf方法。lastIndexOf方法用于查找指定字符或子字符串在字符串中最后一次出现的位置。本文将详细介绍lastIndexOf方法的使用方式、参数含义、返回值以及示例代码。

语法

lastIndexOf方法有多种重载形式,其中最常用的形式为:

public int lastIndexOf(String str)

该方法接受一个字符串参数str,并返回该字符串在调用方法的字符串中最后一次出现的位置。如果未找到,则返回-1。下面是lastIndexOf方法其他常用的重载形式:

  • public int lastIndexOf(String str, int fromIndex):从指定位置fromIndex开始往前搜索字符串str最后一次出现的位置。
  • public int lastIndexOf(int ch):查找指定字符ch在字符串中最后一次出现的位置。
  • public int lastIndexOf(int ch, int fromIndex):从指定位置fromIndex开始往前搜索指定字符ch最后一次出现的位置。

参数含义

  • str:要查找的子字符串。
  • fromIndex:起始搜索位置,从索引fromIndex开始往前搜索。
  • ch:要查找的字符。

返回值

lastIndexOf方法的返回值为整数,表示查找到的子字符串或字符在调用方法的字符串中最后一次出现的位置。如果未找到,则返回-1。

示例代码

下面通过示例代码演示lastIndexOf方法的使用:

public class Main {
    public static void main(String[] args) {
        String str = "Hello World! Hello Java!";
        String subStr = "Hello";

        // 查找子字符串"Hello"最后一次出现的位置
        int lastIndex = str.lastIndexOf(subStr);
        System.out.println("子字符串最后一次出现的位置:" + lastIndex);

        // 从指定位置开始查找子字符串"Hello"最后一次出现的位置
        int fromIndex = 10;
        int lastIndexFromIndex = str.lastIndexOf(subStr, fromIndex);
        System.out.println("从指定位置开始查找子字符串最后一次出现的位置:" + lastIndexFromIndex);

        // 查找字符'W'最后一次出现的位置
        char ch = 'W';
        int lastIndexChar = str.lastIndexOf(ch);
        System.out.println("字符最后一次出现的位置:" + lastIndexChar);
    }
}

运行结果

子字符串最后一次出现的位置:13
从指定位置开始查找子字符串最后一次出现的位置:6
字符最后一次出现的位置:6

上述示例代码中,首先创建了一个字符串str,然后使用lastIndexOf方法查找子字符串”Hello”和字符’W’在字符串中最后一次出现的位置。其中,lastIndexOf(subStr)表示查找子字符串的位置,lastIndexOf(subStr, fromIndex)表示从指定位置开始查找子字符串的位置,lastIndexOf(ch)表示查找字符的位置。

通过运行结果可以看出,子字符串”Hello”最后一次出现的位置为13,从指定位置10开始查找子字符串最后一次出现的位置为6,字符’W’最后一次出现的位置为6。

总结

本文详细介绍了Java中lastIndexOf方法的用法、参数含义、返回值以及示例代码。在实际开发中,我们可以使用lastIndexOf方法来查找字符串中指定字符或子字符串最后一次出现的位置,方便进行字符串处理和分析。

本文链接:http://so.lmcjl.com/news/21686/

展开阅读全文