17.5: The indexOf Method
- Page ID
indexOf method searches for a character in a string.
String fruit = "banana"; int index = fruit.indexOf('a');
This example finds the index of
'a' in the string. But the letter appears three times, so it’s not obvious what
indexOf should do. According to the documentation, it returns the index of the first appearance.
To find subsequent appearances, you can use another version of
indexOf, which takes a second argument that indicates where in the string to start looking.
int index = fruit.indexOf('a', 2);
This code starts at index 2 (the first
'n') and finds the next
'a', which is at index 3. If the letter happens to appear at the starting index, the starting index is the answer. So
fruit.indexOf('a', 5) returns
If the character does not appear in the string,
-1. Since indexes cannot be negative, this value indicates the character was not found.
You can also use
indexOf to search for a substring, not just a single character. For example, the expression