To find the index of the first occurrence of a character in a string in Golang, you can use the strings.Index()
function. Here is an example:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, World!"
char := 'o'
index := strings.IndexRune(str, char)
if index != -1 {
fmt.Printf("The index of the first occurrence of '%c' in '%s' is %d\n", char, str, index)
} else {
fmt.Printf("'%c' not found in '%s'\n", char, str)
}
}
In this example, strings.IndexRune()
function is used to find the index of the first occurrence of the character 'o'
in the string "Hello, World!"
. The function returns the index of the character or -1 if the character is not found.