public class FindOccurrences {
/**
Find all starting indices of a word inside a larger text.
This function uses String.indexOf in a loop. The method is efficient
and implemented in optimized native code, making it ideal for substring search.
*/
public static void findAllOccurrences(String text, String word) {
if (word.isEmpty()) {
return; // Searching for an empty word is meaningless
}
int index = text.indexOf(word); // First occurrence
while (index != -1) {
System.out.println(index); // Print the index
/**
Search again starting one character after the previous match.
This allows detection of overlapping matches.
*/
index = text.indexOf(word, index + 1);
}
}
public static void main(String[] args) {
String text = "the quick brown fox jumps over the lazy dog. the fox is clever.";
String word = "the";
System.out.println("Text: " + text);
System.out.println("Word: \"" + word + "\"\n");
System.out.println("Occurrences at indices:");
findAllOccurrences(text, word);
}
}
/*
run:
Text: the quick brown fox jumps over the lazy dog. the fox is clever.
Word: "the"
Occurrences at indices:
0
31
45
*/