原文: https://beginnersbook.com/2013/12/java-string-lastindexof-method-example/

在上一个教程中,我们讨论了indexOf()方法,该方法用于找出给定String中指定char或子字符串的出现。在本教程中,我们将讨论lastIndexOf()方法,该方法用于找出给定String中或字符子串的最后一次出现的索引。

Java String lastIndexOf()方法签名

要找出指定字符或字符串的最后一次出现,此方法从字符串末尾开始搜索并从那里向后返回。如果在方法调用期间指定了fromIndex,则向后搜索从指定的索引fromIndex开始

int lastIndexOf(int ch):返回给定String中字符ch的最后一次出现。

int lastIndexOf(int ch, int fromIndex):返回ch的最后一次出现,它从指定的索引fromIndex开始向后看。

int lastIndexOf(String str):返回Stringsubstring str的最后一次出现。

int lastIndexOf(String str, int fromIndex):返回str的最后一次出现,开始从指定的索引fromIndex向后搜索。

Java String lastIndexOf()示例

在下面的例子中,我们在String str中搜索几个给定的字符和一个给定的子字符串。我们正在寻找它们在String str中的最后一次出现,这就是我们使用lastIndexOf()方法的原因。如果要查找字符串中char或子字符串的第一次出现,请改用indexOf()方法

  1. public class JavaExample {
  2. public static void main(String[] args) {
  3. String str = "beginnersbook is for beginners";
  4. char ch = 'b';
  5. char ch2 = 's';
  6. String subStr = "beginners";
  7. int posOfB = str.lastIndexOf(ch);
  8. int posOfS = str.lastIndexOf(ch2);
  9. int posOfSubstr = str.lastIndexOf(subStr);
  10. System.out.println(posOfB);
  11. System.out.println(posOfS);
  12. System.out.println(posOfSubstr);
  13. }
  14. }

输出:

Java `String lastIndexOf()`方法 - 图1

String lastIndexOf()方法的另一个例子

这里我们将演示在各种情况下使用lastIndexOf()方法。我们正在尝试使用lastIndexOf()方法的不同变体,我们提供fromIndex,然后该方法从指定的fromIndex向后搜索。

  1. public class LastIndexOfExample{
  2. public static void main(String args[]) {
  3. String str1 = new String("This is a BeginnersBook tutorial");
  4. String str2 = new String("Beginners");
  5. String str3 = new String("Book");
  6. String str4 = new String("Books");
  7. System.out.println("Last 'B' in str1: "+str1.lastIndexOf('B'));
  8. System.out.println("Last 'B' in str1 whose index<=15:"+str1.lastIndexOf('B', 15));
  9. System.out.println("Last 'B' in str1 whose index<=30:"+str1.lastIndexOf('B', 30));
  10. System.out.println("Last occurrence of str2 in str1:"+str1.lastIndexOf(str2));
  11. System.out.println("Last occurrence of str2 in str1 before 15:"+str1.lastIndexOf(str2, 15));
  12. System.out.println("Last occurrence of str3 in str1:"+str1.lastIndexOf(str3));
  13. System.out.println("Last occurrence of str4 in str1"+str1.lastIndexOf(str4));
  14. System.out.println("Last occurrence of 'is' in str1:"+str1.lastIndexOf("is"));
  15. System.out.println("Last occurrence of 'is' in str1 before 4:"+str1.lastIndexOf("is", 4));
  16. }
  17. }

输出:

  1. Last 'B' in str1: 19
  2. Last 'B' in str1 whose index<=15:10
  3. Last 'B' in str1 whose index<=30:19
  4. Last occurrence of str2 in str1:10
  5. Last occurrence of str2 in str1 before 15:10
  6. Last occurrence of str3 in str1:19
  7. Last occurrence of str4 in str1-1
  8. Last occurrence of 'is' in str1:5
  9. Last occurrence of 'is' in str1 before 4:2