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 StringStringindexOflastIndexOf
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.indexOfStringUTF16.indexOf@IntrinsicCandidate
| Method | Since | Returns | Best for |
|---|---|---|---|
indexOf(ch)indexOf(str) | Java 1.0 | First index or -1 | Finding where something starts |
indexOf(ch, from)indexOf(str, from) | Java 1.0 | First index at or after from | Continuing a search; finding all matches |
lastIndexOf | Java 1.0 | Last index or -1 | Extensions, file names, the last separator |
indexOf(ch, begin, end)indexOf(str, begin, end) | Java 21 | First index inside [begin, end) | Searching only part of a string |
containsstartsWithendsWith | Java 5, 1.0, 1.0 | boolean | Yes/no checks |
regionMatches(ignoreCase, ...) | Java 1.0 | boolean | Comparing at a position, optionally ignoring case |
Matcher.find | Java 1.4 | Next match of a regex | Patterns 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 theat
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:
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
is at index 5, ina , because counting starts at 0:cat ,t ,h and the space are 0 to 3, ande is 4.c - With a start position of 6, the search skips that
and finds the one ina at 9.sat skips the first word and finds the secondindexOf("the", 1) at 15.the is -1: the search is case-sensitive.indexOf("The") is also -1.indexOf("dog")- 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
positions, 5, 9 and 20, by starting each search just after the previous match.at , new in Java 21, searches only from 10 up to, but not including, 22, and finds theindexOf('a', 10, 22) ina .mat
Start positions, lastIndexOf and range checks
The fromString
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:
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
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.from returns 22, the length: the empty string is found at the end of the text, and the start is clamped to the length.indexOf("", 100) looks for a match that starts at or beforelastIndexOf(str, 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.from- The Java 21 range methods search
, 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.[begin, end) - Unlike
, the range is checked: an end of 100 threwfrom with "Range [10, 100) out of bounds for length 22".StringIndexOutOfBoundsException - For yes/no questions,
(with an optional offset),startsWith andendsWith say what they mean more clearly than comparing an index with 0 or -1.contains
Finding and counting every occurrence
Finding all matches is the most common use of the from
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:
"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
at 0, 1, 2 and 3 inAA ; moving by the target length finds only 0 and 2, which is whatAAAAA andreplace would see.split - Counting with the length difference after
gives the same 3 as the loop, in one line, but creates a copy of the string.replace - Counting with
gave 1 forsplit(",").length - 1 , which has 2 commas, because"a,b," drops the trailing empty field. Seesplitsplitting strings for the rule. - For patterns,
plays the role of the loop, andMatcher.find gives each position.start() , added in Java 9, returns the matches as a stream, which makes counting a one-liner.Matcher.results()
Cutting strings apart, and the -1 trap
indexOfsubstring
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:
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.@ finds the file name andlastIndexOf('/') the last extension,lastIndexOf('.') ;gz on the name gives the full extension,indexOf('.') .tar.gz - For text between markers, start the second search after the first marker, as
does, so an earlier copy of the closing marker cannot match.html.indexOf("</title>", start) - The trap: for
,README is -1, and -1 + 1 is 0, solastIndexOf('.') returned the whole name as the "extension" without any error. Check for -1 first.substring(0) - Without the + 1, the -1 goes straight into
, which throws "Range [0, -1) out of bounds". That at least fails loudly.substring 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.gitignore
More about extracting parts of a string is on the
Case-insensitive search and Unicode
indexOfİ
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:
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
findsLocale.ROOT at 9. Without an explicit locale,JAVA uses the default one, and in TurkishtoLowerCase() becomesTITLE with a dotless ı, so the search fails on servers set to Turkish.tıtle grew from 18 to 19 characters when lowercased, soİstanbul and Izmir 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.and compares in place, ignoring case, without making copies, and positions stay correct. The helper loop built on it returns 9. AregionMatches(true, ...) withPattern andCASE_INSENSITIVE does the same; addPattern.quote for letters outside ASCII.UNICODE_CASE- Positions count UTF-16 units, not visible characters. The waving-hand emoji needs two of them, so
is at index 6 although only 5 code points come before it.there accepts a code point such asindexOf(int) and finds the emoji at 3. See0x1F44Bcharacters 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.
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):
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
andindexOf took the same time, becausecontains simply callscontains .indexOf- A precompiled literal
was close behind. For a literal pattern of four or more characters,Pattern switches to a Boyer-Moore search (the internalPattern.compile node in the JDK 21 source), which skips ahead after a mismatch.BnM - Lowercasing a copy and then searching was noticeably slower, and it allocates a second 5 million character string on every call.
- The
loop was about three times as slow asregionMatches , and theindexOf regex was the slowest, five to six times slower. Ignoring case costs extra work for every character compared.CASE_INSENSITIVE
Which method to use
| Question | Use |
|---|---|
| Is it there at all? | s.contains(x) |
| Where does it first appear? | s.indexOf(x) |
| Where does it last appear? | s.lastIndexOf(x) |
| Every position | A loop with indexOf(x, i + x.length())i + 1 |
| Only inside part of the string | s.indexOf(x, begin, end) |
| At the start or end | startsWithendsWith |
| Ignoring case, ASCII text | s.toLowerCase(Locale.ROOT).indexOf(x) |
| Ignoring case, positions must match the original | regionMatches(true, ...)CASE_INSENSITIVE |
| A pattern rather than fixed text | Matcher.find |
To replace what you find, see