Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
-1

The last occurrence

lastIndexOf() searches from the end:

void main() {
    IO.println("hello world".lastIndexOf("o"));
}

Output:

7

All 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.com

Common 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 12

Always check if (index != -1) before using the position.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.