//
// Find all starting indices of a word inside a larger text.
// This function uses String.indexOf in a loop. The JVM implements
// substring search in optimized native code, making this approach efficient.
//
def findAllOccurrences(text: String, word: String): List[Int] = {
// Searching for an empty word is meaningless
if (word.isEmpty) return Nil
var indices: List[Int] = Nil
var index: Int = text.indexOf(word) // First occurrence
//
// Loop:
// - If indexOf finds a match, record the index.
// - Then search again starting one character after the previous match.
// This allows detection of overlapping matches.
//
while (index != -1) {
indices = indices :+ index
index = text.indexOf(word, index + 1)
}
indices
}
@main def run(): Unit = {
val text: String =
"the quick brown fox jumps over the lazy dog. the fox is clever."
val word: String = "the"
println(s"Text: $text")
println(s"""Word: "$word"""")
println()
println("Occurrences at indices:")
for (idx <- findAllOccurrences(text, word)) {
println(idx)
}
}
/*
run:
Text: the quick brown fox jumps over the lazy dog. the fox is clever.
Word: "the"
Occurrences at indices:
0
31
45
*/