Finding Multiple Occurrences of a Word
Now that we understand the basics of using indexOf()
to find a single occurrence of a word, let's enhance our skills by learning how to find all occurrences of a word in a string.
Understanding the Second indexOf() Method Signature
The indexOf()
method has another useful form:
int indexOf(String str, int fromIndex)
This version allows you to specify a starting position for the search. By using this form, we can find all occurrences of a word by starting each new search from where we left off.
Creating a Multiple Search Program
Let's create a new Java program that finds all occurrences of a specific word:
- Create a new file named
MultipleFinder.java
- Enter the following code:
public class MultipleFinder {
public static void main(String[] args) {
// Create a sample text with multiple occurrences of a word
String paragraph = "Java is a popular programming language. Java runs on various platforms. " +
"Java is used for developing web applications, mobile apps, and more. " +
"Learning Java is essential for many software development roles.";
System.out.println("Original text:");
System.out.println(paragraph);
System.out.println("\nSearching for all occurrences of 'Java':");
// Find all occurrences of "Java"
String searchWord = "Java";
int position = 0;
int count = 0;
// Loop until no more occurrences are found
while (position != -1) {
position = paragraph.indexOf(searchWord, position);
if (position != -1) {
count++;
System.out.println("Occurrence " + count + " found at position: " + position);
// Move past this occurrence to find the next one
position += searchWord.length();
}
}
System.out.println("\nTotal occurrences found: " + count);
}
}
Compiling and Running the Multiple Search Program
Now let's compile and run our new program:
- In the terminal, compile the Java file:
javac MultipleFinder.java
- Run the compiled program:
java MultipleFinder
You should see output similar to:
Original text:
Java is a popular programming language. Java runs on various platforms. Java is used for developing web applications, mobile apps, and more. Learning Java is essential for many software development roles.
Searching for all occurrences of 'Java':
Occurrence 1 found at position: 0
Occurrence 2 found at position: 42
Occurrence 3 found at position: 72
Occurrence 4 found at position: 149
Total occurrences found: 4
How the Program Works
Let's break down how this program finds all occurrences:
- We set the initial search position to 0 (the beginning of the string)
- We enter a while loop that continues until
indexOf()
returns -1 (no more matches)
- For each match, we:
- Print the position where we found the word
- Update the search position to start after the current match by adding the length of the search word
- The loop continues until no more matches are found
- Finally, we print the total number of occurrences found
Handling Case Sensitivity
The indexOf()
method is case-sensitive by default. Let's modify our program to perform a case-insensitive search by converting both the text and the search term to lowercase:
Add these lines to MultipleFinder.java
right after the main method starts:
// Case-insensitive search demonstration
System.out.println("\n--- Case-insensitive search ---");
String lowercaseParagraph = paragraph.toLowerCase();
String lowercaseSearchWord = searchWord.toLowerCase();
position = 0;
count = 0;
while (position != -1) {
position = lowercaseParagraph.indexOf(lowercaseSearchWord, position);
if (position != -1) {
count++;
System.out.println("Occurrence " + count + " found at position: " + position);
position += lowercaseSearchWord.length();
}
}
System.out.println("\nTotal occurrences found (case-insensitive): " + count);
Compile and run the updated program:
javac MultipleFinder.java
java MultipleFinder
The output will now include both case-sensitive and case-insensitive search results.