String.indexOf()
Finds the position of the first occurrence of a character or a substring.
Available since: Java 1.0
Syntax
public int indexOf(String str, int fromIndex)Parameters
| Parameter | Type | Description |
|---|---|---|
| str | String | What to look for — a string or a char. |
| fromIndex | int | The index to start searching from. Optional; the default is the start. |
Return value
intThe index of the first occurrence, or -1 if nothing is found.
Examples
Searching for a character and a substring:
void main() {
String text = "banana";
IO.println(text.indexOf('n'));
IO.println(text.indexOf("na"));
IO.println(text.indexOf("x"));
}Output:
2
2
-1All occurrences — searching from an offset:
void main() {
String text = "banana";
int i = text.indexOf('a');
while (i != -1) {
IO.println(i);
i = text.indexOf('a', i + 1);
}
}Output:
1
3
5Notes
The search is case-sensitive: "Java".indexOf("j") returns -1. If you only need a yes/no answer, contains() reads better.
See also
- String.lastIndexOf() — Finds the position of the last occurrence of a character or a substring.
- String.contains() — Checks whether a string contains a substring.
- String.substring() — Returns the part of a string between two indexes.
Related recipes
In the tutorial
- String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.