Skip Top Navigation Bar

Finding the Index of a String in Another String, Starting at a Specific Index - Example 2

Snippet: Finding the Index of a String in Another String, Starting at a Specific Index

Explanation

This snippet introduces the two-argument form of indexOf(). The first call finds the first 'o' in "Hello World!", which is at index 4.

To find the next occurrence, indexOf("o", indexOfO + 1) is used — the second argument tells Java where to start searching, skipping past the already-found index.

The second 'o' is at index 7 (in "World"). Searching again from index 8 finds no more 'o' characters, so indexOf() returns -1, signalling that there are no more occurrences.

What You Can Do

Try using the same technique to find all occurrences of "l" in the string. How many are there, and at which indexes?

You can also try searching from index 0 each time instead of advancing the start index — what happens? Do you get stuck finding the same occurrence repeatedly?

Run it and observe the output!

Example List

Additional Resources