Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
strStringWhat to look for — a string or a char.
fromIndexintThe 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
-1

All 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
5

Notes

The search is case-sensitive: "Java".indexOf("j") returns -1. If you only need a yes/no answer, contains() reads better.

See also

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.

Thanks for reading!

Donate to the site — we work hard for you.