How to find the position of a substring
Short answer
indexOf() returns the zero-based index of the first occurrence, or -1 if there is none:
void main() {
String text = "hello world";
IO.println(text.indexOf("o"));
IO.println(text.indexOf("x"));
}Output:
4
-1The last occurrence
lastIndexOf() searches from the end:
void main() {
IO.println("hello world".lastIndexOf("o"));
}Output:
7All occurrences
The second argument of indexOf() sets where to start searching:
void main() {
String text = "abcabcabc";
var positions = new ArrayList<Integer>();
for (int i = text.indexOf("bc"); i != -1; i = text.indexOf("bc", i + 1)) {
positions.add(i);
}
IO.println(positions);
}Output:
[1, 4, 7]Cutting out a part
The position is handy for taking part of the string with substring():
void main() {
String email = "anna@example.com";
int at = email.indexOf('@');
IO.println(email.substring(0, at));
IO.println(email.substring(at + 1));
}Output:
anna
example.comCommon mistake
Not checking for -1. Then substring() gets a negative index and throws an exception:
void main() {
String text = "no separator";
int index = text.indexOf(':');
IO.println(text.substring(index + 1, index));
}Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [0, -1) out of bounds for length 12Always check if (index != -1) before using the position.
Functions used in this recipe
- String.indexOf() — Finds the position of the first occurrence of a character or a substring.
- String.lastIndexOf() — Finds the position of the last occurrence of a character or a substring.
- String.substring() — Returns the part of a string between two indexes.
- String.contains() — Checks whether a string contains a substring.