Choose a Scenario
Found by indexOf
First extraction
Second extraction
Third extraction
Exclusive end (not included)
Step 0 / 0
Try It Yourself
Enter a string and a delimiter to see how indexOf() and substring() would split it.
Shortcut: split()
When you just need all the pieces, split() does it in one call:
Tip: Use
indexOf() + substring() when you need precise control over which part you extract. Use split() when you want all pieces at once.
Key Concepts
indexOf(String target)
Returns the index of the first occurrence of
targetReturns
-1 if not foundlastIndexOf(String target)
Returns the index of the last occurrence of
targetUseful when delimiter appears more than once
substring(int start)
Returns chars from
start to the end of the stringOne argument = "from here to the end"
substring(int start, int end)
Returns chars from
start up to but NOT including endThe end index is EXCLUSIVE — this is the #1 source of confusion!
Common Mistake: Thinking
substring(0, 4) includes index 4. It does NOT. It returns characters at indices 0, 1, 2, 3 only.
The Pattern
// Find the delimiter
int pos = str.indexOf("-");
// Get left part
String left = str.substring(0, pos);
// Get right part
String right = str.substring(pos + 1);
int pos = str.indexOf("-");
// Get left part
String left = str.substring(0, pos);
// Get right part
String right = str.substring(pos + 1);
Why pos + 1? Because
pos is the index of the delimiter itself. We want to start after it, so we add 1.