In Java, the indexOf()
function is used to find the index of a specific character or substring.
In case the function successfully locates the character or substring, the starting index is returned. If not, -1 is returned.
There are four variants of the indexOf()
function. Let’s look at each of them in detail.
This returns the index of the first occurrence of the character ch
in the given string.
ch
- the character to search forclass HelloWorld {public static void main( String args[] ) {String str = "Hello!";System.out.printf("o is located at index: %d", str.indexOf('o'));}}
This variant of the indexOf() function searches for the first occurrence of the character ch
starting from the specified index, searchFrom
, of the string.
ch
- the character to search forsearchFrom
- the index where the search will begin fromclass HelloWorld {public static void main( String args[] ) {String str = "Hello!";System.out.printf("l is located at index: %d", str.indexOf('l',3));}}
This variant of the indexOf() function returns the index at which the first occurrence of the String str starts.
str
- the string to search forclass HelloWorld {public static void main( String args[] ) {String str = "Image!";System.out.printf("age is located at index: %d", str.indexOf("age"));}}
This variant of the indexOf() function returns the starting index of the first occurrence of the String str, starting the search from the specified index, searchFrom, of the string.
str
- the string to search forsearchFrom
- the index where the search will begin fromAs the substring age is not located ahead of the third index, the function will return -1.
class HelloWorld {public static void main( String args[] ) {String str = "Image!";System.out.printf("age is located at index: %d", str.indexOf("age", 3));}}