Latest web development tutorials

Java lastIndexOf () method

Java String class Java String class


There are four forms lastIndexOf () method:

  • public int lastIndexOf (int ch): Returns the characters in this string of the last index appears if no such character string, it returns -1.

  • public int lastIndexOf (int ch, int fromIndex): return Returns the specified character index within this string of the last occurrence, if no such character string, it returns -1.

  • public int lastIndexOf (String str): Returns the characters in this string of the last index appears if no such character string, it returns -1.

  • public int lastIndexOf (String str, int fromIndex): Returns the characters in this string of the last index appears if no such character string, it returns -1.

grammar

public int lastIndexOf(int ch)

或

public int lastIndexOf(int ch, int fromIndex)

或

public int lastIndexOf(String str)

或

public int lastIndexOf(String str, int fromIndex)

parameter

  • ch - the character.

  • fromIndex - the index to start the search.

  • str - the substring to search for.

return value

Index value of the first occurrence of the specified substring in the string.

Examples

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 ));
	}
}

The above program execution results:

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

Java String class Java String class