How to find the last index value of a string in Golang?

Go ProgrammingServer Side ProgrammingProgramming

LastIndex() is a built-in function of strings package in Golang. This function is used to check the index of the last occurrence of a specified substring in a given original string. If the substring is found in the given string, then it returns its index position, starting from 0; otherwise it returns "-1".

Syntax

The syntax of LastIndex() is −

func LastIndex(str, substr string) int

Where,

  • str is the string inside which we need to search, and
  • substr is the substring that we want to search inside the str.

Example 1

Let us consider the following example −

package main
import (
   "fmt"
   "strings"
)
func main() {
   
   // Initializing the Strings
   p := "Programming Language"
   q := "String Function"
   r := "Golang String Function"
   s := "1234512345"

   // Display the Strings
   fmt.Println("String 1:", p)
   fmt.Println("String 2:", q)
   fmt.Println("String 3:", r)
   fmt.Println("String 4:", s)

   // Using the LastIndex Function
   test1 := strings.LastIndex(p, "ge")
   test2 := strings.LastIndex(q, "C")
   test3 := strings.LastIndex(r, "ng")
   test4 := strings.LastIndex(s, "23")

   // Display the LastIndex Output
   fmt.Println("LastIndex of 'ge' in String 1:", test1)
   fmt.Println("LastIndex of 'C' in String 2:", test2)
   fmt.Println("LastIndex of 'ng' in String 3:", test3)
   fmt.Println("LastIndex of '23' in String 4:", test4)
}

Output

It will generate the following output −

String 1: Programming Language
String 2: String Function
String 3: Golang String Function
String 4: 1234512345
LastIndex of 'ge' in String 1: 18
LastIndex of 'C' in String 2: -1
LastIndex of 'ng' in String 3: 11
LastIndex of '23' in String 4: 6

Observe that LastIndex() is case-sensitive; hence it returns "-1" for test2.

Example 2

Let us take another example.

package main
import (
   "fmt"
   "strings"
)
func main() {
   var x string
   var y string

   // Intializing the Strings
   x = "LastIndex"
   y = "LastIndex Function"

   // Display the Strings
   fmt.Println("String 1:", x)
   fmt.Println("String 2:", y)

   // See if y is found in x using LastIndex Function
   if strings.LastIndex(y, x) != -1 {
      fmt.Println("String 2 is found in String 1")
   } else {
      fmt.Println("String 2 is not found in String 1")
   }
}

Output

It will generate the following output −

String 1: LastIndex
String 2: LastIndex Function
String 2 is found in String 1
raja
Updated on 10-Mar-2022 09:35:58

Advertisements