Latest web development tutorials

Java lastIndexOf() 方法

Java String類 Java String類


lastIndexOf() 方法有以下四種形式:

  • public int lastIndexOf(int ch):返回指定字符在此字符串中最後一次出現處的索引,如果此字符串中沒有這樣的字符,則返回-1。

  • public int lastIndexOf(int ch, int fromIndex):返返回指定字符在此字符串中最後一次出現處的索引,如果此字符串中沒有這樣的字符,則返回-1。

  • public int lastIndexOf(String str):返回指定字符在此字符串中最後一次出現處的索引,如果此字符串中沒有這樣的字符,則返回-1。

  • public int lastIndexOf(String str, int fromIndex):返回指定字符在此字符串中最後一次出現處的索引,如果此字符串中沒有這樣的字符,則返回-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 --要搜索的子字符串。

返回值

指定子字符串在字符串中第一次出現處的索引值。

實例

public class Test {
	public static void main(String args[]) {
		String Str = new String("本教程:www.w3big.com");
		String SubStr1 = new String("w3big");
		String SubStr2 = new String("com");

		System.out.print("查找字符 o 最后出现的位置 :" );
		System.out.println(Str.lastIndexOf( 'o' ));
		System.out.print("从第14个位置查找字符 o 最后出现的位置 :" );
		System.out.println(Str.lastIndexOf( 'o', 14 ));
		System.out.print("子字符串 SubStr1 最后出现的位置:" );
		System.out.println( Str.lastIndexOf( SubStr1 ));
		System.out.print("从第十五个位置开始搜索子字符串 SubStr1最后出现的位置 :" );
		System.out.println( Str.lastIndexOf( SubStr1, 15 ));
		System.out.print("子字符串 SubStr2 最后出现的位置 :" );
		System.out.println(Str.lastIndexOf( SubStr2 ));
	}
}

以上程序執行結果為:

查找字符 o 最后出现的位置 :17
从第14个位置查找字符 o 最后出现的位置 :13
子字符串 SubStr1 最后出现的位置:9
从第十五个位置开始搜索子字符串 SubStr1最后出现的位置 :9
子字符串 SubStr2 最后出现的位置 :16

Java String類 Java String類