strings.LastIndex() method in Golang

We have already discussed the Index() method of the strings package, which returns the first occurrence of the substring within the specified string. This post will discuss the LastIndex() method of the strings package, which returns the last occurrence of the substring within the specified substring.

  • Method declaration – func LastIndex(s, substr string) int
  • What does it do? It returns the last occurrence of the string substr within the string s.
    • This means that if there are multiple occurrences of the string substr in the string s, then it is going to return the last occurrence of the string substr
  • What does it return? LastIndex() method returns an int value representing the last occurrence of the string substr within the string s. It will return -1 if there are no occurrences of the string substr in the string s

Code Example

package main

import (
	"fmt"
	"strings"
)

func main() {

	index1 := strings.LastIndex("codekru", "kru")               // this will return 4
	index2 := strings.LastIndex("codekru", "Hi")                // this will return -1
	index3 := strings.LastIndex("hello codekru hello", "hello") // this will return 14

	fmt.Println("Last index of kru in the string is:", index1)
	fmt.Println("Last index of hi in the string is:", index2)
	fmt.Println("Last index of hello in the string is:", index3)

}

Output –

Last index of kru in the string is: 4
Last index of hi in the string is: -1
Last index of hello in the string is: 14

The What If scenarios

What if we pass an empty string as the substring?

If the length of the string is 0, then the method will return the specified string’s length ( passed in the first argument ) as illustrated by the below program.

package main

import (
	"fmt"
	"strings"
)

func main() {

	index := strings.LastIndex("codekru", "") // this will return 7

	fmt.Println("Last index of empty string is:", index)

}

Output –

Last index of empty string is: 7
What if both strings passed in the method’s arguments are empty?

In this case, the method will return the length of the string passed in the first argument, which is also 0 in this scenario.

package main

import (
	"fmt"
	"strings"
)

func main() {

	index := strings.LastIndex("", "") // this will return 0

	fmt.Println("Last index of empty string is:", index)

}

Output –

Last index of empty string is: 0

Please visit this link to learn more about the Strings in Go language and its other functions or methods.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *