indexOf and lastIndexOf

indexOf returns the position where a character or substring first appears in a string, and lastIndexOf the position where it last appears; both return -1 when there is none. This page explains how positions are counted, runs every variant including the Java 21 range methods, finds all occurrences, shows the -1 and case-insensitivity traps, and compares search speed.

Contents

How indexOf searches a string

A String stores its text as an array of UTF-16 code units, and every position in the String API is an index into that array, starting at 0. The indexOf method scans forward from a start position and returns the index of the first character of the first match. lastIndexOf scans backward and returns the start of the last match. When there is no match, both return -1 rather than throwing, so the caller must check the result.

The search is a straightforward comparison at each position, but it is fast in practice. Strings with only Latin-1 characters are stored one byte per character (compact strings, Java 9), and the JDK marks the internal StringLatin1.indexOf and StringUTF16.indexOf methods @IntrinsicCandidate, so HotSpot can replace them with an intrinsic: hand-written machine code that compares many bytes per instruction on common CPUs.

Search methods on String
MethodSinceReturnsBest for
indexOf(ch), indexOf(str)Java 1.0First index or -1Finding where something starts
indexOf(ch, from), indexOf(str, from)Java 1.0First index at or after fromContinuing a search; finding all matches
lastIndexOf (4 forms)Java 1.0Last index or -1Extensions, file names, the last separator
indexOf(ch, begin, end), indexOf(str, begin, end)Java 21First index inside [begin, end)Searching only part of a string
contains, startsWith, endsWithJava 5, 1.0, 1.0booleanYes/no checks
regionMatches(ignoreCase, ...)Java 1.0booleanComparing at a position, optionally ignoring case
Matcher.findJava 1.4Next match of a regexPatterns rather than fixed text

The programs below were compiled and run on JDK 21, which is needed for the range methods.

The basic forms

The test sentence is short enough to count by hand and contains the substrings the and at several times, so the difference between first, next and last match is visible.

Java
public class IndexOfDemo {

    public static void main(String[] args) {
        String text = "the cat sat on the mat";
        //             0123456789...

        System.out.println("indexOf('a')          = " + text.indexOf('a'));
        System.out.println("indexOf('a', 6)       = " + text.indexOf('a', 6));
        System.out.println("indexOf(\"the\")        = " + text.indexOf("the"));
        System.out.println("indexOf(\"the\", 1)     = " + text.indexOf("the", 1));
        System.out.println("lastIndexOf(\"at\")     = " + text.lastIndexOf("at"));
        System.out.println("indexOf(\"dog\")        = " + text.indexOf("dog"));
        System.out.println("indexOf(\"The\")        = " + text.indexOf("The"));
        System.out.println("indexOf(\"\")           = " + text.indexOf(""));

        // Every occurrence: start each search just after the previous match
        StringBuilder found = new StringBuilder();
        for (int i = text.indexOf("at"); i >= 0; i = text.indexOf("at", i + 1)) {
            found.append(i).append(' ');
        }
        System.out.println("all \"at\" positions:   " + found.toString().trim());

        // Java 21: search only inside a range [begin, end)
        System.out.println("indexOf('a', 10, 22)  = " + text.indexOf('a', 10, 22));
    }
}

Output:

Output
indexOf('a')          = 5
indexOf('a', 6)       = 9
indexOf("the")        = 0
indexOf("the", 1)     = 15
lastIndexOf("at")     = 20
indexOf("dog")        = -1
indexOf("The")        = -1
indexOf("")           = 0
all "at" positions:   5 9 20
indexOf('a', 10, 22)  = 20
  • The first a is at index 5, in cat, because counting starts at 0: t, h, e and the space are 0 to 3, and c is 4.
  • With a start position of 6, the search skips that a and finds the one in sat at 9. indexOf("the", 1) skips the first word and finds the second the at 15.
  • indexOf("The") is -1: the search is case-sensitive. indexOf("dog") is also -1.
  • The empty string is found at the start position, here 0. Every string "contains" the empty string at every index.
  • The loop finds all three at positions, 5, 9 and 20, by starting each search just after the previous match.
  • indexOf('a', 10, 22), new in Java 21, searches only from 10 up to, but not including, 22, and finds the a in mat.

Start positions, lastIndexOf and range checks

The from argument has rules that differ from the rest of the String API: most methods throw on a bad index, but these do not. The same sentence is used, with deliberately out-of-range positions.

Java
public class EdgeCases {

    public static void main(String[] args) {
        String text = "the cat sat on the mat";

        // fromIndex is forgiving: out-of-range values do not throw
        System.out.println("indexOf('t', -5)        = " + text.indexOf('t', -5));
        System.out.println("indexOf('t', 100)       = " + text.indexOf('t', 100));
        System.out.println("indexOf(\"\", 100)        = " + text.indexOf("", 100));
        System.out.println("length()                = " + text.length());

        // lastIndexOf searches backwards, starting AT fromIndex
        System.out.println("lastIndexOf(\"at\")       = " + text.lastIndexOf("at"));
        System.out.println("lastIndexOf(\"at\", 19)   = " + text.lastIndexOf("at", 19));
        System.out.println("lastIndexOf(\"at\", 9)    = " + text.lastIndexOf("at", 9));
        System.out.println("lastIndexOf(\"at\", 8)    = " + text.lastIndexOf("at", 8));
        System.out.println("lastIndexOf(\"\")         = " + text.lastIndexOf(""));

        // Java 21 range versions search [beginIndex, endIndex) and DO check the range
        System.out.println("indexOf('a', 10, 20)    = " + text.indexOf('a', 10, 20));
        System.out.println("indexOf(\"at\", 10, 21)   = " + text.indexOf("at", 10, 21));
        System.out.println("indexOf(\"at\", 10, 22)   = " + text.indexOf("at", 10, 22));
        try {
            text.indexOf('a', 10, 100);
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("indexOf('a', 10, 100)   -> " + e.getMessage());
        }

        // Related checks that are clearer than comparing indexOf with 0 or -1
        System.out.println("startsWith(\"cat\", 4)    = " + text.startsWith("cat", 4));
        System.out.println("endsWith(\"mat\")         = " + text.endsWith("mat"));
        System.out.println("contains(\"sat on\")      = " + text.contains("sat on"));
    }
}

Output:

Output
indexOf('t', -5)        = 0
indexOf('t', 100)       = -1
indexOf("", 100)        = 22
length()                = 22
lastIndexOf("at")       = 20
lastIndexOf("at", 19)   = 9
lastIndexOf("at", 9)    = 9
lastIndexOf("at", 8)    = 5
lastIndexOf("")         = 22
indexOf('a', 10, 20)    = -1
indexOf("at", 10, 21)   = -1
indexOf("at", 10, 22)   = 20
indexOf('a', 10, 100)   -> Range [10, 100) out of bounds for length 22
startsWith("cat", 4)    = true
endsWith("mat")         = true
contains("sat on")      = true
  • A negative from is treated as 0, and one past the end returns -1. No exception is thrown, which makes loops simple but also hides off-by-one bugs.
  • indexOf("", 100) returns 22, the length: the empty string is found at the end of the text, and the start is clamped to the length.
  • lastIndexOf(str, from) looks for a match that starts at or before from. With 19 it skipped the match starting at 20 and found 9. With 9 it still found 9, and with 8 it went back to 5.
  • The Java 21 range methods search [begin, end), and a match must fit entirely inside. With end 21, the match that occupies 20 and 21 does not fit, so the result is -1; with end 22 it is found.
  • Unlike from, the range is checked: an end of 100 threw StringIndexOutOfBoundsException with "Range [10, 100) out of bounds for length 22".
  • For yes/no questions, startsWith (with an optional offset), endsWith and contains say what they mean more clearly than comparing an index with 0 or -1.

Finding and counting every occurrence

Finding all matches is the most common use of the from argument. The inputs include a string of repeated letters, where matches can overlap, and a list with a trailing separator, which breaks a popular counting trick.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AllOccurrences {

    public static void main(String[] args) {
        String text = "the cat sat on the mat";
        System.out.println("\"at\" at " + positions(text, "at", false));

        // Overlapping matches: step 1 vs step target.length()
        String dna = "AAAAA";
        System.out.println("\"AA\" overlapping:     " + positions(dna, "AA", true));
        System.out.println("\"AA\" non-overlapping: " + positions(dna, "AA", false));

        // Counting: a loop, or the length difference after removing the target
        String log = "ERROR a; INFO b; ERROR c; ERROR d";
        System.out.println("ERROR count (loop):    " + positions(log, "ERROR", false).size());
        int byLength = (log.length() - log.replace("ERROR", "").length()) / "ERROR".length();
        System.out.println("ERROR count (replace): " + byLength);

        // The split trick miscounts when the target is at the end
        String trailing = "a,b,";
        System.out.println("commas in \"a,b,\" via split: " + (trailing.split(",").length - 1)
            + ", via loop: " + positions(trailing, ",", false).size());

        // Regex find gives positions of pattern matches
        Matcher m = Pattern.compile("\\b\\w{3}\\b").matcher(text);
        List<String> words = new ArrayList<>();
        while (m.find()) {
            words.add(m.group() + "@" + m.start());
        }
        System.out.println("3-letter words: " + words);
        long count = Pattern.compile("at").matcher(text).results().count();
        System.out.println("matches count:  " + count);
    }

    static List<Integer> positions(String text, String target, boolean overlapping) {
        List<Integer> found = new ArrayList<>();
        int step = overlapping ? 1 : target.length();
        for (int i = text.indexOf(target); i >= 0; i = text.indexOf(target, i + step)) {
            found.add(i);
        }
        return found;
    }
}

Output:

Output
"at" at [5, 9, 20]
"AA" overlapping:     [0, 1, 2, 3]
"AA" non-overlapping: [0, 2]
ERROR count (loop):    3
ERROR count (replace): 3
commas in "a,b," via split: 1, via loop: 2
3-letter words: [the@0, cat@4, sat@8, the@15, mat@19]
matches count:  3
  • How far to move after each match decides whether matches may overlap. Moving by 1 finds AA at 0, 1, 2 and 3 in AAAAA; moving by the target length finds only 0 and 2, which is what replace and split would see.
  • Counting with the length difference after replace gives the same 3 as the loop, in one line, but creates a copy of the string.
  • Counting with split(",").length - 1 gave 1 for "a,b,", which has 2 commas, because split drops the trailing empty field. See splitting strings for the rule.
  • For patterns, Matcher.find plays the role of the loop, and start() gives each position. Matcher.results(), added in Java 9, returns the matches as a stream, which makes counting a one-liner.

Cutting strings apart, and the -1 trap

indexOf is usually paired with substring to extract part of a value. The inputs are an email address, a path with a double extension, a tag pair, and three values where the separator is missing or in an awkward place.

Java
public class IndexOfUses {

    public static void main(String[] args) {
        String email = "maria.lopez@example.org";
        int at = email.indexOf('@');
        System.out.println("user: " + email.substring(0, at)
            + ", domain: " + email.substring(at + 1));

        // lastIndexOf for the part after the last separator
        String file = "/var/log/archive.tar.gz";
        System.out.println("file name:  " + file.substring(file.lastIndexOf('/') + 1));
        System.out.println("extension:  " + file.substring(file.lastIndexOf('.') + 1));
        String name = file.substring(file.lastIndexOf('/') + 1);
        System.out.println("full ext:   " + name.substring(name.indexOf('.') + 1));

        // Text between two markers
        String html = "<title>Order 42</title>";
        int start = html.indexOf("<title>") + "<title>".length();
        int end = html.indexOf("</title>", start);
        System.out.println("between:    " + html.substring(start, end));

        // The -1 trap: -1 + 1 is 0, so substring silently returns the whole string
        String noExt = "README";
        System.out.println("unchecked:  [" + noExt.substring(noExt.lastIndexOf('.') + 1) + "]");
        int dot = noExt.lastIndexOf('.');
        System.out.println("checked:    [" + (dot < 0 ? "" : noExt.substring(dot + 1)) + "]");

        // Without + 1 the -1 goes straight into substring, which throws
        String noAt = "not-an-email";
        try {
            System.out.println(noAt.substring(0, noAt.indexOf('@')));
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("substring(0, -1) -> " + e.getMessage());
        }

        // A hidden file: lastIndexOf('.') is 0, so the "extension" is the whole name
        String hidden = ".gitignore";
        String ext = hidden.substring(hidden.lastIndexOf('.') + 1);
        System.out.println(".gitignore ext: [" + ext + "]");
    }
}

Output:

Output
user: maria.lopez, domain: example.org
file name:  archive.tar.gz
extension:  gz
full ext:   tar.gz
between:    Order 42
unchecked:  [README]
checked:    []
substring(0, -1) -> Range [0, -1) out of bounds for length 12
.gitignore ext: [gitignore]
  • Splitting at the @ gives the user and domain. lastIndexOf('/') finds the file name and lastIndexOf('.') the last extension, gz; indexOf('.') on the name gives the full extension, tar.gz.
  • For text between markers, start the second search after the first marker, as html.indexOf("</title>", start) does, so an earlier copy of the closing marker cannot match.
  • The trap: for README, lastIndexOf('.') is -1, and -1 + 1 is 0, so substring(0) returned the whole name as the "extension" without any error. Check for -1 first.
  • Without the + 1, the -1 goes straight into substring, which throws "Range [0, -1) out of bounds". That at least fails loudly.
  • .gitignore has its only dot at index 0, so the naive code reports gitignore as the extension. Real file-name code treats a leading dot as part of the name.

More about extracting parts of a string is on the substring page.

Case-insensitive search and Unicode

indexOf has no ignore-case option, and the usual workaround, lowercasing both strings, has two traps. The inputs are chosen to trigger them: the letter I in Turkish, and the capital dotted İ, which becomes two characters in lowercase. An emoji shows how positions are counted.

Java
import java.util.Locale;
import java.util.regex.Pattern;

public class CaseAndUnicode {

    public static void main(String[] args) {
        String title = "Learning JAVA Streams";

        // Case-insensitive: lower-case both sides with a fixed locale
        System.out.println("indexOf(\"java\")              = " + title.indexOf("java"));
        System.out.println("lowercase ROOT, indexOf      = "
            + title.toLowerCase(Locale.ROOT).indexOf("java"));

        // The default locale can change the result: Turkish lowercases I to dotless i
        String upper = "TITLE";
        Locale turkish = Locale.forLanguageTag("tr");
        System.out.println("TITLE lower (tr) = " + upper.toLowerCase(turkish)
            + ", indexOf(\"title\") = " + upper.toLowerCase(turkish).indexOf("title"));

        // Lowercasing can change the length, so indexes no longer fit the original
        String city = "İstanbul and Izmir";
        String lower = city.toLowerCase(Locale.ROOT);
        System.out.println("length " + city.length() + " -> " + lower.length()
            + ", \"and\" at " + city.indexOf("and") + " in original, "
            + lower.indexOf("and") + " in lowercase");

        // regionMatches compares in place, without creating lowercase copies
        System.out.println("regionMatches(true, 9, \"java\") = "
            + title.regionMatches(true, 9, "java", 0, 4));
        System.out.println("first case-insensitive match  = " + indexOfIgnoreCase(title, "java"));
        Pattern ci = Pattern.compile(Pattern.quote("java"), Pattern.CASE_INSENSITIVE);
        var m = ci.matcher(title);
        System.out.println("Pattern CASE_INSENSITIVE      = " + (m.find() ? m.start() : -1));

        // Indexes count UTF-16 chars: an emoji takes two
        String chat = "Hi 👋 there";
        System.out.println("indexOf(\"there\") = " + chat.indexOf("there")
            + ", code points before it = " + chat.codePointCount(0, chat.indexOf("there")));
        System.out.println("indexOf(0x1F44B) = " + chat.indexOf(0x1F44B));
    }

    static int indexOfIgnoreCase(String text, String target) {
        for (int i = 0; i <= text.length() - target.length(); i++) {
            if (text.regionMatches(true, i, target, 0, target.length())) {
                return i;
            }
        }
        return -1;
    }
}

Output:

Output
indexOf("java")              = -1
lowercase ROOT, indexOf      = 9
TITLE lower (tr) = tıtle, indexOf("title") = -1
length 18 -> 19, "and" at 9 in original, 10 in lowercase
regionMatches(true, 9, "java") = true
first case-insensitive match  = 9
Pattern CASE_INSENSITIVE      = 9
indexOf("there") = 6, code points before it = 5
indexOf(0x1F44B) = 3
  • Lowercasing with Locale.ROOT finds JAVA at 9. Without an explicit locale, toLowerCase() uses the default one, and in Turkish TITLE becomes tıtle with a dotless ı, so the search fails on servers set to Turkish.
  • İstanbul and Izmir grew from 18 to 19 characters when lowercased, so and is at 9 in the original but at 10 in the copy. An index found in a lowercased copy does not always point to the right place in the original.
  • regionMatches(true, ...) compares in place, ignoring case, without making copies, and positions stay correct. The helper loop built on it returns 9. A Pattern with CASE_INSENSITIVE and Pattern.quote does the same; add UNICODE_CASE for letters outside ASCII.
  • Positions count UTF-16 units, not visible characters. The waving-hand emoji needs two of them, so there is at index 6 although only 5 code points come before it. indexOf(int) accepts a code point such as 0x1F44B and finds the emoji at 3. See characters and code points.

How fast is each search?

The program searches a 5 million character string of random letters for a word placed at the very end, so every approach has to scan the whole text. Each approach runs 10 searches, 3 times, and the best time is reported.

Java
import java.util.Locale;
import java.util.Random;
import java.util.function.ToIntFunction;
import java.util.regex.Pattern;

public class SearchSpeed {

    static final Pattern LITERAL = Pattern.compile("needle");
    static final Pattern IGNORE_CASE = Pattern.compile("needle", Pattern.CASE_INSENSITIVE);

    public static void main(String[] args) {
        Random random = new Random(7);
        StringBuilder sb = new StringBuilder();
        while (sb.length() < 5000000) {
            sb.append((char) ('a' + random.nextInt(26)));
        }
        sb.append("needle");
        String hay = sb.toString();
        System.out.printf("search a %,d-char string for a word at the end%n", hay.length());

        time("indexOf", hay, s -> s.indexOf("needle"));
        time("contains", hay, s -> s.contains("needle") ? 1 : 0);
        time("Pattern.find", hay, s -> {
            var m = LITERAL.matcher(s);
            return m.find() ? m.start() : -1;
        });
        time("toLowerCase + indexOf", hay, s -> s.toLowerCase(Locale.ROOT).indexOf("needle"));
        time("Pattern CASE_INSENSITIVE", hay, s -> {
            var m = IGNORE_CASE.matcher(s);
            return m.find() ? m.start() : -1;
        });
        time("regionMatches loop", hay, s -> {
            for (int i = 0; i <= s.length() - 6; i++) {
                if (s.regionMatches(true, i, "needle", 0, 6)) {
                    return i;
                }
            }
            return -1;
        });
    }

    // Best of 3 runs of 10 searches each
    static void time(String name, String hay, ToIntFunction<String> f) {
        long best = Long.MAX_VALUE;
        int result = 0;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            for (int i = 0; i < 10; i++) {
                result = f.applyAsInt(hay);
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-26s %7.1f ms per 10 searches  result %d%n", name, best / 1e6, result);
    }
}

Output (rough comparison on a 2-CPU Linux machine, JDK 21; times differ on other machines):

Output
search a 5,000,006-char string for a word at the end
indexOf                       33.5 ms per 10 searches  result 5000000
contains                      33.0 ms per 10 searches  result 1
Pattern.find                  45.2 ms per 10 searches  result 5000000
toLowerCase + indexOf         55.2 ms per 10 searches  result 5000000
Pattern CASE_INSENSITIVE     177.8 ms per 10 searches  result 5000000
regionMatches loop            91.3 ms per 10 searches  result 5000000
  • indexOf and contains took the same time, because contains simply calls indexOf.
  • A precompiled literal Pattern was close behind. For a literal pattern of four or more characters, Pattern.compile switches to a Boyer-Moore search (the internal BnM node in the JDK 21 source), which skips ahead after a mismatch.
  • Lowercasing a copy and then searching was noticeably slower, and it allocates a second 5 million character string on every call.
  • The regionMatches loop was about three times as slow as indexOf, and the CASE_INSENSITIVE regex was the slowest, five to six times slower. Ignoring case costs extra work for every character compared.

Which method to use

Choosing a search method
QuestionUse
Is it there at all?s.contains(x)
Where does it first appear?s.indexOf(x), then check for -1
Where does it last appear?s.lastIndexOf(x)
Every positionA loop with indexOf(x, i + x.length()), or i + 1 for overlaps
Only inside part of the strings.indexOf(x, begin, end) (Java 21)
At the start or endstartsWith, endsWith
Ignoring case, ASCII texts.toLowerCase(Locale.ROOT).indexOf(x)
Ignoring case, positions must match the originalregionMatches(true, ...) or a CASE_INSENSITIVE pattern
A pattern rather than fixed textMatcher.find; see regular expressions

To replace what you find, see replacing text in a string.