What is the LastIndex function in Golang?

Overview

The LastIndex function is used to find the index of the last instance of a substring in a string value.

To use this function, we must import the strings package in our file and access the LastIndex function within it, using the . notation (string.LastIndex).

Syntax

The definition of the LastIndex function is as follows:

func LastIndex(str, substr string) int

Parameters

The LastIndex function takes two arguments.

  • str: This is the argument of the type string that we want to search inside of.

  • substr: This is the string argument that represents the value that we want to search for inside the str.

Return value

The LastIndex function returns the index of the last instance of the substring found inside the str. -1 is returned if the substring is not found inside str.

Example code

package main
import (
"fmt"
"strings"
)
func main() {
str:= "Education from Educative"
sbstr1:= "Ed"
sbstr2:= "Ad"
check1:= strings.LastIndex(str,sbstr1)
check2:= strings.LastIndex(str,sbstr2)
fmt.Println("Inside \"", str,"\"")
if check1 != -1{
fmt.Println(sbstr1, " is present at", check1)
} else {
fmt.Println(sbstr1, " is not found:", )
}
if check2 != -1{
fmt.Println(sbstr2, " is present at", check2 )
} else {
fmt.Println(sbstr2, " is not fonud:", check2)
}
}

Explanation

In the above code, we do the following:

  • Lines 3-6: We import the fmt and strings packages.

  • Line 8: We start the main function.

  • Lines 10-13: We initialize the string variables str, substr1, and substr2.

  • Lines 15-16: We run the LastIndex function, trying to find substr1 and substr2 in str and storing the respective values in check1 and check2.

  • Lines 21-25: We print the return value of LastIndex if substr1 was found in str. Otherwise, we print is not found.

  • Lines 27-31: We print the return value of the LastIndex if substr2 was found in str. Otherwise, we print is not found.

Free Resources