Go – Index of Last Occurrence of Substring in String

To get the index of last occurrence of a substring in a string in Go programming, call LastIndex function of strings package, and pass the string and substring as arguments to this function.

The syntax to get the index of the last occurrence of substring substr in a string str using LastIndex function is

strings.LastIndex(str, substr)

LastIndex function returns an integer that represents the position of last occurrence of substr in str.

Examples

In the following program, we will take a string Welcome to Go Tutorial, Go Examples and find the index of last occurrence of substring Go.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str = "Welcome to Go Tutorial, Go Examples"
	var substr = "Go"
	var index = strings.LastIndex(str, substr)
	fmt.Println("The index of last occurrence of substring is: ", index)
}

Output

The index of last occurrence of substring is:  24

If the substring is not present in the input string, LastIndex returns -1.

In the following program, we will take a string and substring such that substring is not present in the string. We will then use LastIndex function to find the index of last occurrence of substring in given string. Since substring is not present in the string, LastIndex should return -1.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str = "Welcome to Go Tutorial, Go Examples"
	var substr = "Python"
	var index = strings.LastIndex(str, substr)
	fmt.Println("The index of last occurrence of substring is: ", index)
}

Output

The index of last occurrence of substring is:  -1
ADVERTISEMENT

Conclusion

In this Golang Tutorial, we learned how to find the index of last occurrence of a substring in given string using strings.LastIndex() function.