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 typestringthat we want to search inside of. -
substr: This is thestringargument that represents the value that we want to search for inside thestr.
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 mainimport ("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
fmtandstringspackages. -
Line 8: We start the
mainfunction. -
Lines 10-13: We initialize the
stringvariablesstr,substr1, andsubstr2. -
Lines 15-16: We run the
LastIndexfunction, trying to findsubstr1andsubstr2instrand storing the respective values incheck1andcheck2. -
Lines 21-25: We print the return value of
LastIndexifsubstr1was found instr. Otherwise, we printis not found. -
Lines 27-31: We print the return value of the
LastIndexifsubstr2was found instr. Otherwise, we printis not found.