OneBite.Dev - Coding blog in a bite size

find the last occurrence of a character in a string in Go

Code snippet on how to find the last occurrence of a character in a string in Go

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Hello, world!"
	index := strings.LastIndex(str, "l")
	fmt.Println(index)
}

This code example is written in Go, and finds the last occurrence of a character in a string. First, the code imports the “strings” and “fmt” packages. Next, it defines a “str” variable as the string to search. Then, the code calls the strings package’s “LastIndex()” function, passing in the “str” variable and the character to find. This function returns the index of the last occurrence of the character in the string. Finally, the code prints the index of the character in the string.

go