String中的lastIndexOf方法,是獲取要搜索的字符、字符串最后次出現的位置。
可以看到有四個重載方法分別是:
public int lastIndexOf(int ch); public int lastIndexOf(int ch, int fromIndex); public int lastIndexOf(String str); public int lastIndexOf(String str, int fromIndex);
四個方法,其中第一、第二個方法時對char(字符)進行匹配,區別在於第二個方法多了個參數 fromIndex,該參數的含義是從String(字符串)中的第幾位開始向前進行匹配。
同理第三個和第四個方法時對字符串進行匹配,第四個方法可以申明開始向前匹配的位置。
示例1如下:
public class Test { public static void main(String[] args) { String str = "sdasaq"; System.out.println(str.lastIndexOf('a')); // 4 System.out.println(str.lastIndexOf('a', 3)); // 2 System.out.println(str.lastIndexOf("as")); // 2 System.out.println(str.lastIndexOf("as", 1)); // 1 } }
示例2如下:
int x = a.lastIndexOf(b); // 表示b字符串在a字符串中最后出現的位置。從0開始。 如:a= "abcdabcd"; b="d"; 那么x的值為7
示例3如下:
指定字符串最后出現的位置,從0開始: System.out.println("abcde".lastIndexOf("c")); // 輸出2 System.out.println("abcdec".lastIndexOf("c")); // 輸出5