原文: 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):返回String中substring str的最后一次出现。
int lastIndexOf(String str, int fromIndex):返回str的最后一次出现,开始从指定的索引fromIndex向后搜索。
Java String lastIndexOf()示例
在下面的例子中,我们在String str中搜索几个给定的字符和一个给定的子字符串。我们正在寻找它们在String str中的最后一次出现,这就是我们使用lastIndexOf()方法的原因。如果要查找字符串中char或子字符串的第一次出现,请改用indexOf()方法。
public class JavaExample {public static void main(String[] args) {String str = "beginnersbook is for beginners";char ch = 'b';char ch2 = 's';String subStr = "beginners";int posOfB = str.lastIndexOf(ch);int posOfS = str.lastIndexOf(ch2);int posOfSubstr = str.lastIndexOf(subStr);System.out.println(posOfB);System.out.println(posOfS);System.out.println(posOfSubstr);}}
输出:

String lastIndexOf()方法的另一个例子
这里我们将演示在各种情况下使用lastIndexOf()方法。我们正在尝试使用lastIndexOf()方法的不同变体,我们提供fromIndex,然后该方法从指定的fromIndex向后搜索。
public class LastIndexOfExample{public static void main(String args[]) {String str1 = new String("This is a BeginnersBook tutorial");String str2 = new String("Beginners");String str3 = new String("Book");String str4 = new String("Books");System.out.println("Last 'B' in str1: "+str1.lastIndexOf('B'));System.out.println("Last 'B' in str1 whose index<=15:"+str1.lastIndexOf('B', 15));System.out.println("Last 'B' in str1 whose index<=30:"+str1.lastIndexOf('B', 30));System.out.println("Last occurrence of str2 in str1:"+str1.lastIndexOf(str2));System.out.println("Last occurrence of str2 in str1 before 15:"+str1.lastIndexOf(str2, 15));System.out.println("Last occurrence of str3 in str1:"+str1.lastIndexOf(str3));System.out.println("Last occurrence of str4 in str1"+str1.lastIndexOf(str4));System.out.println("Last occurrence of 'is' in str1:"+str1.lastIndexOf("is"));System.out.println("Last occurrence of 'is' in str1 before 4:"+str1.lastIndexOf("is", 4));}}
输出:
Last 'B' in str1: 19Last 'B' in str1 whose index<=15:10Last 'B' in str1 whose index<=30:19Last occurrence of str2 in str1:10Last occurrence of str2 in str1 before 15:10Last occurrence of str3 in str1:19Last occurrence of str4 in str1-1Last occurrence of 'is' in str1:5Last occurrence of 'is' in str1 before 4:2
