Returns the index within this String of the first occurrence of the specified substring. This method has 4 different variants.
public int indexOf(int ch) − Returns the index within this string of the first occurrence of the specified character or -1 if the character does not occur.
public int indexOf(int ch)
ch – The character to search for in the string.
Returns the index within this string of the first occurrence of the specified character or -1 if the character does not occur.
public int indexOf(int ch, int fromIndex) − Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index or 1 if the character does not occur.
public int indexOf(int ch, int fromIndex)
ch − The character to search for in the string
fromIndex − where to start the search from
Return Value
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index or -1 if the character does not occur.
int indexOf(String str) − Returns the index within this string of the first occurrence of the specified substring. If it does not occur as a substring, -1 is returned.
int indexOf(String str)
Str – The string to search for
Return Value
Returns the index within this string of the first occurrence of the specified substring. If it does not occur as a substring, -1 is returned.
int indexOf(String str, int fromIndex) − Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is returned.
int indexOf(String str, int fromIndex)
str – The string to search for
Return Value − Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is returned.
Following is an example of the usage of all 4 method variants
class Example { static void main(String[] args) { String a = "Hello World"; // Using public int indexOf(int ch) println(a.indexOf('e')); println(a.indexOf('o')); // Using public int indexOf(int ch, int fromIndex) println(a.indexOf('l',1)); println(a.indexOf('e',4)); // Using public int indexOf(string str) println(a.indexOf('el')); println(a.indexOf('or')); // Using public int indexOf(string str,int fromIndex) println(a.indexOf('el',1)); println(a.indexOf('or',8)); } }
When we run the above program, we will get the following result −
1 4 2 -1 1 7 1 -1