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

In Go, a string is a sequence of bytes that represents a text. Each character in the string is represented by one or more bytes.

To find the first index of a character in a string, we need to convert the string to a slice of runes using the built-in rune function, and then iterate over the slice to find the index of the target character.

Here's an example code snippet:

main.go
func findIndex(s string, c rune) int {
    for i, r := range s {
        if r == c {
            return i
        }
    }
    return -1
}

func main() {
    s := "hello, world"
    c := 'l'
    idx := findIndex(s, c)
    fmt.Println(idx) // Output: 2
}
253 chars
16 lines

In this example, we define a function findIndex that takes a string s and a rune c as input, and returns the index of the first occurrence of c in s. If c is not found in s, the function returns -1.

In the main function, we call findIndex with the string s and the rune c='l', and print the index of the first occurrence of l in the string s, which is 2.

Note that we use the range keyword to iterate over the slice of runes. This is because each character in a Go string can be represented by one or more bytes, and the range keyword ensures that we iterate over the characters (runes) instead of the bytes.

gistlibby LogSnag