find the kth index of a substring in a string in go

To find the kth index of a substring in a string in Go, we can use the strings package and a simple loop. Here's a code snippet that demonstrates this:

main.go
import "strings"

func findKthIndex(s, substr string, k int) int {
    idx := -1
    for i := 0; i < k; i++ {
        idx = strings.Index(s, substr)
        if idx == -1 {
            return -1
        }
        s = s[idx+len(substr):]
    }
    return idx
}
259 chars
14 lines

This function takes in a string s, a substring substr, and an integer k indicating which index of the substring to find. It then loops k times, looking for the substring in the current version of s. If it finds it, it updates s to start at the end of the previous match (i.e., idx+len(substr)). If it doesn't find the substring, it returns -1. Finally, it returns the index of the kth occurrence of substr in s.

Here's an example of using this function:

main.go
s := "hello world, hello go"
substr := "hello"
k := 2
idx := findKthIndex(s, substr, k)
fmt.Printf("The %dth occurrence of '%s' in '%s' is at index %d\n", k, substr, s, idx)
// Output: The 2nd occurrence of 'hello' in 'hello world, hello go' is at index 13
257 chars
7 lines

This will output the index of the second occurrence of substr in s. Note that this function assumes that there are at least k occurrences of substr in s. If this is not the case, it will return -1.

gistlibby LogSnag