Java 教程
lastIndexOf() 方法有以下四種形式:
public int lastIndexOf(int ch): 返回指定字符在此字符串中最后一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
public int lastIndexOf(int ch, int fromIndex): 返回指定字符在此字符串中最后一次出現(xiàn)處的索引,從指定的索引處開始進(jìn)行反向搜索,如果此字符串中沒有這樣的字符,則返回 -1。
public int lastIndexOf(String str): 返回指定子字符串在此字符串中最右邊出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
public int lastIndexOf(String str, int fromIndex): 返回指定子字符串在此字符串中最后一次出現(xiàn)處的索引,從指定的索引開始反向搜索,如果此字符串中沒有這樣的字符,則返回 -1。
public int lastIndexOf(int ch) 或 public int lastIndexOf(int ch, int fromIndex) 或 public int lastIndexOf(String str) 或 public int lastIndexOf(String str, int fromIndex)
ch -- 字符。
fromIndex -- 開始搜索的索引位置。
str -- 要搜索的子字符串。
指定子字符串在字符串中第一次出現(xiàn)處的索引值。
public class Test { ????public static void main(String args[]) { ????????String Str = new String("小白教程:"); ????????String SubStr1 = new String("json"); ????????String SubStr2 = new String("com"); ????????System.out.print("查找字符 o 最后出現(xiàn)的位置 :" ); ????????System.out.println(Str.lastIndexOf( 'o' )); ????????System.out.print("從第14個位置查找字符 o 最后出現(xiàn)的位置 :" ); ????????System.out.println(Str.lastIndexOf( 'o', 14 )); ????????System.out.print("子字符串 SubStr1 最后出現(xiàn)的位置:" ); ????????System.out.println( Str.lastIndexOf( SubStr1 )); ????????System.out.print("從第十五個位置開始搜索子字符串 SubStr1最后出現(xiàn)的位置 :" ); ????????System.out.println( Str.lastIndexOf( SubStr1, 15 )); ????????System.out.print("子字符串 SubStr2 最后出現(xiàn)的位置 :" ); ????????System.out.println(Str.lastIndexOf( SubStr2 )); ????} }
以上程序執(zhí)行結(jié)果為:
查找字符 o 最后出現(xiàn)的位置 :17 從第14個位置查找字符 o 最后出現(xiàn)的位置 :13 子字符串 SubStr1 最后出現(xiàn)的位置:9 從第十五個位置開始搜索子字符串 SubStr1最后出現(xiàn)的位置 :9 子字符串 SubStr2 最后出現(xiàn)的位置 :16