Java String indexOf() Example: Find Substring Position
This Snippet is coded by a user inOnline java Compiler. You can see and run this code too.
زبان: Java
The following Java code demonstrates the usage of the indexOf() method from the String class. This method returns the index of the first occurrence of a specified substring within a string.
In this example, the string "Please locate where 'locate' occurs!" is defined, and by calling indexOf("locate"), the starting index of the substring “locate” is returned. The output is 7, as “locate” begins at index 7.
- If the substring is not found,
indexOf()returns -1. - Overloaded versions like
indexOf(String str, int fromIndex)allow searching from a specific index. - The
lastIndexOf()method finds the last occurrence of the substring.
This method is essential for string manipulation, parsing, and text processing in Java applications.