To find the index of the last occurrence of a substring in Go, you can use the strings.LastIndex
function.
In this example,
strings
package for string manipulation.str
with a string value.strings.LastIndex
function to find the index of the last occurrence of a specific substring within str
.strings.LastIndex
function returns the index of the last occurrence of the substring in the string.package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello World, Hello Go"
lastIndex := strings.LastIndex(str, "Hello")
fmt.Println("Last index of substring is:", lastIndex)
}
Last index of substring is: 13
In this example,
strings
package for string manipulation.str1
and str2
with different values.strings.LastIndex
function to find the index of the last occurrence of str2
within str1
.strings.LastIndex
function returns the index of the last occurrence of str2
in str1
.package main
import (
"fmt"
"strings"
)
func main() {
str1 := "apple banana cherry banana"
str2 := "banana"
lastIndex := strings.LastIndex(str1, str2)
fmt.Println("Last index of substring is:", lastIndex)
}
Last index of substring is: 20
In this tutorial, we learned How to find the Index of Last Occurrence of Substring in Go language with well detailed examples.