To find the indices of all occurrences of a substring in Go, you can iterate through the string and use the strings.Index
function.
In this example,
fmt
and strings
packages.findAllIndices
that takes two strings, str
and substr
, as parameters.indices
to store the starting indices of each occurrence of the substring.strings.Index
function, starting from a given index.indices
slice and update the starting index for the next search to be after the current occurrence.indices
slice.main
function, we define a string str
and a substring substr
with specific values.findAllIndices
function with str
and substr
and store the result in the variable indices
.indices
to standard output.package main
import (
"fmt"
"strings"
)
func findAllIndices(str, substr string) []int {
var indices []int
index := strings.Index(str, substr)
for index != -1 {
indices = append(indices, index)
index = strings.Index(str[index+len(substr):], substr)
if index != -1 {
index += indices[len(indices)-1] + len(substr)
}
}
return indices
}
func main() {
str := "Hello World, Hello Universe, Hello Go"
substr := "Hello"
indices := findAllIndices(str, substr)
fmt.Println("Indices of all occurrences:", indices)
}
Indices of all occurrences: [0 13 29]
In this example,
fmt
and strings
packages.findAllIndices
function to find all occurrences of a substring within a string.main
function, we define a different string str
and a different substring substr
with specific values.findAllIndices
function with str
and substr
and store the result in the variable indices
.indices
to standard output.package main
import (
"fmt"
"strings"
)
func findAllIndices(str, substr string) []int {
var indices []int
index := strings.Index(str, substr)
for index != -1 {
indices = append(indices, index)
index = strings.Index(str[index+len(substr):], substr)
if index != -1 {
index += indices[len(indices)-1] + len(substr)
}
}
return indices
}
func main() {
str := "Go is great. Go is fast. Go is fun."
substr := "Go"
indices := findAllIndices(str, substr)
fmt.Println("Indices of all occurrences:", indices)
}
Indices of all occurrences: [0 13 25]
In this tutorial, we learned How to find the Indices of All Occurrences of Substring in Go language with well detailed examples.