📜  Java.lang.String.lastIndexOf() 方法

📅  最后修改于: 2022-05-13 01:54:35.583000             🧑  作者: Mango

Java .lang.String.lastIndexOf() 方法

lastIndexOf() 方法有四种变体。本文描述了所有变体,如下所示:
1. lastIndexOf():该方法返回字符序列中字符最后一次出现的索引。

Syntax:
int lastIndexOf(int ch)
Parameters:
ch : a character.
Return Value:
This method returns the index.
// Java code to demonstrate the
// working of lastIndexOf()
public class L_index1 {
  
public static void main(String args[])
    {
  
        // Initialising String
        String Str = new String("Welcome to geeksforgeeks");
  
        System.out.print("Found Last Index of g at : ");
  
        // Last index of 'g' will print
        // prints 19
        System.out.println(Str.lastIndexOf('g'));
    }
}

输出:

Found Last Index of g at : 19

2. lastIndexOf(int ch, int beg) :该方法返回该对象表示的字符序列中小于等于beg的字符最后一次出现的索引,如果之前没有字符则返回-1那一点。

Syntax:
public int lastIndexOf(int ch, int beg)
Parameters:
ch : a character.
beg : the index to start the search from.
Returned Value:
This method returns the index.
// Java code to demonstrate the
// working of lastIndexOf()
public class L_index2 {
  
public static void main(String args[])
    {
  
        // Initialising String
        String Str = new String("Welcome to geeksforgeeks");
  
        System.out.print("Found Last Index of g at : ");
  
        // Last index of 'g' before 15 will print
        // prints 11
        System.out.println(Str.lastIndexOf('g', 15));
    }
}

输出:

Found Last Index of g at : 11

3. lastIndexOf(String str) :此方法接受一个字符串作为参数,如果字符串参数作为该对象中的子字符串出现一次或多次,则返回最后一个此类子字符串的第一个字符的索引。如果它不作为子字符串出现,则返回 -1。

Syntax:
public int lastIndexOf(String str)
Parameters:
str : a string.
Returned Value:
This method returns the index.
// Java code to demonstrate the
// working of lastIndexOf(String str)
public class L_index3 {
  
public static void main(String args[])
    {
  
        // Initialising String
        String Str = new String("Welcome to geeksforgeeks");
  
        System.out.print("Found substring geeks at : ");
  
        // start index of last occurrence of "geeks'
        // prints 19
        System.out.println(Str.lastIndexOf("geeks"));
    }
}

输出:

Found substring geeks at : 19

4. lastIndexOf(String str, int beg) :该方法返回该字符串中指定子字符串最后一次出现的索引,从指定索引开始向后搜索。

Syntax:
public int lastIndexOf(String str, int beg)
Parameters
beg : the index to start the search from.
str : a string.
Return Value
This method returns the index.
// Java code to demonstrate the
// working of lastIndexOf(String str,  int beg)
public class L_index4 {
  
public static void main(String args[])
    {
  
        // Initialising String
        String Str = new String("Welcome to geeksforgeeks");
  
        System.out.print("Found substring geeks at : ");
  
        // start index of last occurrence of "geeks'
        // before 15
        // prints 11
        System.out.println(Str.lastIndexOf("geeks", 15));
    }
}

输出:

Found substring geeks at : 11