Latest web development tutorials

Java indexOf () method

Java String class Java String class


There are four forms indexOf () method:

  • public int indexOf (int ch): Returns the character index of the first occurrence of the string, if no such character string, it returns -1.

  • public int indexOf (int ch, int fromIndex): Returns the character in the string index of the first occurrence, if no such character string, it returns -1.

  • int indexOf (String str): Returns the character in the string index of the first occurrence, if no such character string, it returns -1.

  • int indexOf (String str, int fromIndex ): Returns the character in the string index of the first occurrence, if no such character string, it returns -1.

grammar

public int indexOf(int ch )

或

public int indexOf(int ch, int fromIndex)

或

int indexOf(String str)

或

int indexOf(String str, int fromIndex)

parameter

  • ch - the character.

  • fromIndex - the index to start the search.

  • str - the substring to search for.

return value

Specified substring in the string index of the first occurrence, starting at the specified index.

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.indexOf( 'o' ));
		System.out.print("从第14个位置查找字符 o 第一次出现的位置 :" );
		System.out.println(Str.indexOf( 'o', 14 ));
		System.out.print("子字符串 SubStr1 第一次出现的位置:" );
		System.out.println( Str.indexOf( SubStr1 ));
		System.out.print("从第十五个位置开始搜索子字符串 SubStr1 第一次出现的位置 :" );
		System.out.println( Str.indexOf( SubStr1, 15 ));
		System.out.print("子字符串 SubStr2 第一次出现的位置 :" );
		System.out.println(Str.indexOf( SubStr2 ));
	}
}

The above program execution results:

查找字符 o 第一次出现的位置 :12
从第14个位置查找字符 o 第一次出现的位置 :17
子字符串 SubStr1 第一次出现的位置:9
从第十五个位置开始搜索子字符串 SubStr1 第一次出现的位置 :-1
子字符串 SubStr2 第一次出现的位置 :16

Java String class Java String class