Skip to content

Java String indexOf Example

Java String indexOf example shows how to search a string within a string using the indexOf method. The example also shows how to use indexOf to search all occurrences of a string within a String.

How to search character or string within a string using Java String indexOf?

To search a character or string within String, you can use the indexOf method of String class.

These method return index of the first occurrence of a string or character within the String. The indexOf method returns -1 if the specified string or char is not found in the source String object.

Java String indexOf example

Output

You can also use the indexOf method to search a particular character in the String as given below.

Output

Note: The indexOf method does not accept regular expressions. If you want to specify the regular expression for searching a substring, use the matches method of String class.

How to search character or string within String after the specified index?

If you want to search for character or string within the string after the specified index position, you can use the indexOf method that accepts the start index as a parameter.

These methods return the index of the first occurrence of the specified character or string within the String starting from the startIndex parameter.

For example, if you want to search the index of “o” starting from index 5, you can use below given code.

Output

How to find all occurrences of character or string within String?

If you want to find all occurrences of character or string within the string, you can use while loop along with the indexOf method as given below.

Output

Note: If you just want to check if the string contains a specified character or String, please check out the Java String Contains example. If you want to check if the string contains a number, please check out the check if String contains a number example.

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.