Java lastIndexOf() Method

Java String类Java String Class


The lastIndexOf() method has the following four forms:

  • public int lastIndexOf(int ch):Returns the index of the last occurrence of the specified character in this string, or -1 if there is no such character in this string.

  • public int lastIndexOf(int ch, int fromIndex):Returns the index of the last occurrence of the specified character in this string, searching backward from the specified index, or -1 if there is no such character in this string.

  • public int lastIndexOf(String str):Returns the index of the rightmost occurrence of the specified substring in this string, or -1 if there is no such character in this string.

  • public int lastIndexOf(String str, int fromIndex):Returns the index of the last occurrence of the specified substring in this string, searching backward from the specified index, or -1 if there is no such character in this string.

Syntax

public int lastIndexOf(int ch)

或

public int lastIndexOf(int ch, int fromIndex)

或

public int lastIndexOf(String str)

或

public int lastIndexOf(String str, int fromIndex)

Parameters

  • ch-- character.

  • fromIndex-- the index position to start the search.

  • str-- the substring to search for.

Return Value

The index value of the first occurrence of the specified substring in the string.

Example

public class Test {
    public static void main(String args[]) {
        String Str = new String("Example:www.example.com");
        String SubStr1 = new String("example");
        String SubStr2 = new String("com");

        System.out.print("查找字符 o 最后出现的位置 :" );
        System.out.println(Str.lastIndexOf( 'o' ));
        System.out.print("从第14个位置查找字符 o 最后出现的位置 :" );
        System.out.println(Str.lastIndexOf( 'o', 14 ));
        System.out.print("子字符串 SubStr1 最后出现的位置:" );
        System.out.println( Str.lastIndexOf( SubStr1 ));
        System.out.print("从第十五个位置开始搜索子字符串 SubStr1最后出现的位置 :" );
        System.out.println( Str.lastIndexOf( SubStr1, 15 ));
        System.out.print("子字符串 SubStr2 最后出现的位置 :" );
        System.out.println(Str.lastIndexOf( SubStr2 ));
    }
}

The execution result of the above program is:

查找字符 o 最后出现的位置 :17
从第14个位置查找字符 o 最后出现的位置 :13
子字符串 SubStr1 最后出现的位置:9
从第十五个位置开始搜索子字符串 SubStr1最后出现的位置 :9
子字符串 SubStr2 最后出现的位置 :16

Java String类Java String Class

Other Extensions