Java String Handling

Java String indexOf Example

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

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

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

These method return index of first occurrence of a string or character within the String. 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: indexOf method does not accept regular expressions. If you want to specify the regular expression for searching a substring, use matches method of String class.

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

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

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

For example, if you want to search 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 specified character or String, please see Java String Contains example. If you want to check if String contains number, please see check if String contains number example.

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

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *