String.indexOf() / lastIndexOf() / contains()
Methods for searching for a specific string within a string, or checking whether it is present. The search result is returned as an index (position); if not found, -1 is returned.
Syntax
// Returns the index of the first match (or -1 if not found). string.indexOf(String str); string.indexOf(String str, int fromIndex); // Returns the index of the last match (or -1 if not found). string.lastIndexOf(String str); string.lastIndexOf(String str, int fromIndex); // Returns whether the string contains the specified sequence. string.contains(CharSequence s);
Method List
| Method | Description |
|---|---|
| indexOf(String str) | Returns the index of the first occurrence of the specified string. Returns -1 if not found. |
| indexOf(String str, int fromIndex) | Searches forward starting from the position specified by fromIndex. |
| lastIndexOf(String str) | Returns the index of the last occurrence of the specified string. Returns -1 if not found. |
| lastIndexOf(String str, int fromIndex) | Searches backward starting from the position specified by fromIndex. |
| contains(CharSequence s) | Returns true if the string contains the specified sequence, or false otherwise. |
Sample Code
// Use indexOf() to get the position of the first occurrence.
String str = "banana";
System.out.println(str.indexOf("an")); // Prints "1".
// Returns -1 if the substring is not found.
System.out.println(str.indexOf("xyz")); // Prints "-1".
// Search starting from a specified position.
System.out.println(str.indexOf("an", 2)); // Prints "3".
// Use lastIndexOf() to get the position of the last occurrence.
String text = "abcabc";
System.out.println(text.lastIndexOf("b")); // Prints "4".
// Use contains() to check whether a substring is present.
String sentence = "Java is an object-oriented language.";
System.out.println(sentence.contains("Java")); // Prints "true".
System.out.println(sentence.contains("Python")); // Prints "false".
// You can also use indexOf() to check for the existence of a substring.
if (str.indexOf("nan") != -1) {
System.out.println("'nan' was found.");
}
Notes
indexOf() returns the index of the first occurrence of the specified substring within the string. Indexes are zero-based, and -1 is returned if the substring is not found. You can pass a starting position as the second argument to begin the search partway through the string.
contains() internally calls indexOf() and is convenient when you want a boolean result rather than a position. Both methods are case-sensitive. If you need a case-insensitive search, convert the string with toLowerCase() or similar before comparing.
To check for matches at the beginning or end of a string, use startsWith() / endsWith(). To extract a substring, use substring().
If you find any errors or copyright issues, please contact us.