Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.indexOf — finding a substring

String.indexOf returns the position of the first substring match or -1. The fromIndex parameter lets you start searching at a specified position.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

int position = text.indexOf(str);
int positionFromIndex = text.indexOf(str, fromIndex);

String.indexOf(str) finds the first substring match; String.indexOf(str, fromIndex) searches starting at fromIndex, inclusively. The result is a zero-based index into the entire string, or -1. Test position >= 0, not position > 0: position 0 is a valid match.

Searching is literal, case-sensitive, and does not interpret regular expressions. Indices count UTF-16 code units (char), not necessarily whole Unicode characters. A negative fromIndex acts like 0; for nonempty str, an index beyond the string length yields -1. An out-of-range index alone does not cause an exception.

An empty str yields Math.min(Math.max(fromIndex, 0), text.length()). A null argument for str causes NullPointerException. To find the next, potentially overlapping match of a nonempty substring, start at position + 1 after a successful match.

Examples

public class Main {
    public static void main(String[] args) {
        String text = "banana";
        int first = text.indexOf("ana");
        int next = text.indexOf("ana", first + 1);
        System.out.println(first);
        System.out.println(next);
        System.out.println(text.indexOf("ANA"));
        System.out.println(text.indexOf("", 99));
    }
}

Result

1
3
-1
6

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources