Skip to content
Related Articles

Related Articles

strings.LastIndex() Function in Golang With Examples
  • Last Updated : 19 Apr, 2020

strings.LastIndex() function in the Golang returns the starting index of the occurrence of the last instance of a substring in a given string. If the substring is not found then it returns -1. Thus, this function returns an integer value. The index is counted taking zero as the starting index of the string.

Syntax:

func LastIndex(str, substring string) int

Here, str is the original string and substring is a string, whose we want to find the last index value.

Example 1:




// Golang program to illustrate the
// strings.LastIndex() Function
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    // taking a string
    str := "GeeksforGeeks"
    substr := "Geeks"
    fmt.Println(strings.LastIndex(str, substr))
  
}

Output:



8

The string is “GeeksforGeeks” and the substring is “Geeks” so the compiler finds the substring present in the original string and displays the starting index of the last instance of substring which is 8.

Example 2:




// Golang program to illustrate the
// strings.LastIndex() Function
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    // taking strings
    str := "My favorite sport is football"
    substr1 := "f"
    substr2 := "ll"
    substr3 := "SPORT"
  
    // using the function
    fmt.Println(strings.LastIndex(str, substr1))
    fmt.Println(strings.LastIndex(str, substr2))
    fmt.Println(strings.LastIndex(str, substr3))
}

Output:

21
27
-1

The string is “My favorite sport is football” and the substrings are “f”, “ll” and “SPORT” so the compiler displays the output as 21 and 27 in the first two cases respectively and since the third substring is “SPORT” which is considered as not present in the string as the function is case sensitive so it will give the result as -1.

My Personal Notes arrow_drop_up
Recommended Articles
Page :