package main
import (
"fmt"
"strings"
)
/*
Find all starting indices of a word inside a larger text.
This function uses strings.Index in a loop. The search is efficient
because Go's standard library implements optimized substring matching.
*/
func findAllOccurrences(text string, word string) []int {
indices := []int{}
// Searching for an empty word is meaningless
if len(word) == 0 {
return indices
}
// First occurrence
index := strings.Index(text, word)
for index != -1 {
indices = append(indices, index) // Store the index
/*
Search again starting one character after the previous match.
This allows detection of overlapping matches.
*/
index = strings.Index(text[index+1:], word)
if index != -1 {
index += indices[len(indices)-1] + 1
}
}
return indices
}
func main() {
text := "the quick brown fox jumps over the lazy dog. the fox is clever."
word := "the"
fmt.Println("Text:", text)
fmt.Printf("Word: %q\n\n", word)
fmt.Println("Occurrences at indices:")
for _, idx := range findAllOccurrences(text, word) {
fmt.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
*/