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

To find the kth index of a character in a string in Go, you can use the strings.Index() function. Here is an example:

main.go
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "Hello, world!"

	// find the 4th index of the 'o' character
	k := 4
	i := -1
	for j := 0; j < k; j++ {
		i = strings.Index(s[i+1:], "o")
		if i == -1 {
			break
		}
	}

	if i >= 0 {
		fmt.Printf("The %dth index of 'o' in \"%s\" is %d\n", k, s, i+1)
	} else {
		fmt.Printf("Could not find the %dth index of 'o' in \"%s\"\n", k, s)
	}
}
400 chars
27 lines

In the example above, we use a loop to find the kth index of the 'o' character in the string "Hello, world!". We increment the starting index i by 1 each time we call strings.Index() to find the next occurrence of 'o'. If we cannot find a kth occurrence of 'o', we display a message indicating that it was not found.

gistlibby LogSnag