Library contents

Java String.indexOf

Return the offset of the first matching character or substring within the requested search range.

A simple example

String.indexOf

  1. Start with "aba", looking for b
  2. Do this Find the first match
  3. Result Index 1 (zero-based)
Scanning from the left reaches b after one character.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("aba".indexOf("b"));
    }
}
Output
1

Syntax

Java syntax
public int indexOf(int ch)
JDK 21 method signatures (6)
public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(int ch, int beginIndex, int endIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
public int indexOf(String str, int beginIndex, int endIndex)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Locate a separator on a parcel label

A compound filename or route code uses punctuation to separate fields. Decide whether the first or last separator marks the desired boundary before extracting the field next to it.

From the programString parcel = "BLR-482"
Result3
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String parcel = "BLR-482";
        System.out.println(parcel.indexOf('-'));
    }
}
Output
3

The hyphen follows three letters.

Advertisements

Search only the first shipment field

A shipment label contains several fields that might contain similar text. Limit the search to the requested field and confirm how its boundaries affect the result.

From the programString row = "AIR|SEA|AIR"
Result-1
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String row = "AIR|SEA|AIR";
        System.out.println(row.indexOf("AIR", 4, 7));
    }
}
Output
-1

The range from four through six contains SEA. The later AIR lies outside it.

Read a parcel sorting code

The depot scans a parcel marked NC-17. Find the dash in this identifier. How many characters precede the matching separator?

GivenNC-17
Worked result2

What to watch for

Offsets are UTF-16 units. A missing match returns -1. The bounded overloads require valid begin and end offsets.

Documentation for String.indexOf