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.go259 chars14 linesThis 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.go257 chars7 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