Suffixarray Lookup Repeated Offsets
Index text with index/suffixarray and query it with Lookup and FindAllIndex to collect every occurrence offset of a pattern.
Code
package main
import (
"fmt"
"index/suffixarray"
)
func main() {
text := []byte("banana bandana ananas")
index := suffixarray.New(text)
// Lookup returns every starting offset of the pattern
offsets := index.Lookup([]byte("ana"), -1)
fmt.Println("ana offsets:", offsets)
fmt.Println("ana count:", len(offsets))
// a negative limit means no limit, a positive one caps the result
capped := index.Lookup([]byte("an"), 3)
fmt.Println("first three an:", capped)
// FindAllIndex returns [start, end] pairs instead of start offsets
spans := index.FindAllIndex([]byte("band"), -1)
fmt.Println("band spans:", spans)
// a missing pattern produces an empty result rather than an error
fmt.Println("missing:", index.Lookup([]byte("kiwi"), -1))
}How the snippet works
Under the hood: the function main.
Points of care
- Built-in APIs only, so there is no supply chain to vet.
Using it
The demo output is labeled (ana offsets:, ana count:, first three an:), so each line traces straight back to the statement that printed it.
Key statements
spans := index.FindAllIndex([]byte("band"), -1)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Suffixarray Lookup Repeated Offsets print when run?
- No setup needed: run the file and look for labeled lines like `ana offsets:`, `ana count:`, `first three an:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.