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
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: Introduction to String Indexing
- Learn: Comparing Two String Objects Using compareTo Methods
- Learn: Comparing String Objects with equals Methods
- Learn: Obtaining Substrings from a String Object
- Learn: Using the split method on a String
- Practice: Evaluating Expressions that use the String Class
- Practice: Writing Code Using the String Class
- FRQ Practice: AP Computer Science A FRQ 1 Formatting Words
- FRQ Practice: AP Computer Science A FRQ 1 Sentence Analysis