find the position of the last occurrence of a substring in a string in Go
Code snippet on how to find the position of the last occurrence of a substring in a string in Go
func lastIndexOfSubstring(str string, substr string) int {
lastIndex := -1
for i := 0; i < len(str); i++ {
if str[i:i + len(substr)] == substr {
lastIndex = i
}
}
return lastIndex
}
This code finds the position of the last occurrence of a substring in a string in Go. It begins by setting the lastIndex variable to -1, which will be the value returned if there is no occurrence of the substring. It then iterates through the string (str) character by character. For each character, it uses an if statement to compare the substring (substr) to the current position. If the substring and the current position match, it updates the lastIndex variable to the current position. Finally, it returns the lastIndex variable.