Home »
Golang »
Golang Reference
Golang strings.LastIndex() Function with Examples
Golang | strings.LastIndex() Function: Here, we are going to learn about the LastIndex() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 17, 2021
strings.LastIndex()
The LastIndex() function is an inbuilt function of strings package which is used to get the index of the last occurrence (instance) of the substring in a string. It accepts two parameters – string and substring and returns the last index, or returns -1 if the substring is not present in the string.
Syntax
func LastIndex(str, substr string) int
Parameters
- str : String in which we have to check the last index substring.
- substr : Substring to be checked in the string.
Return Value
The return type of the LastIndex() function is an int, it returns the index of the last occurrence (instance) of the substring in a string, or -1 if the substring is not present in the string.
Example 1
// Golang program to demonstrate the
// example of strings.LastIndex() Function
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.LastIndex("Hello, world", "world"))
fmt.Println(strings.LastIndex("abcdabba", "ab"))
fmt.Println(strings.LastIndex("abcdabba", "ce"))
}
Output:
7
4
-1
Example 2
// Golang program to demonstrate the
// example of strings.LastIndex() Function
package main
import (
"fmt"
"strings"
)
func main() {
var str string
var substr string
var index int
str = "Hello, world!"
substr = "world"
index = strings.LastIndex(str, substr)
if index >= 0 {
fmt.Printf("Last index of %q in %q is %d.\n", substr, str, index)
} else {
fmt.Printf("%q does not found in %q.\n", substr, str)
}
str = "Hello, world!"
substr = "l"
index = strings.LastIndex(str, substr)
if index >= 0 {
fmt.Printf("Last index of %q in %q is %d.\n", substr, str, index)
} else {
fmt.Printf("%q does not found in %q.\n", substr, str)
}
str = "Hello! Hi! How are you?"
substr = "H"
index = strings.LastIndex(str, substr)
if index >= 0 {
fmt.Printf("Last index of %q in %q is %d.\n", substr, str, index)
} else {
fmt.Printf("%q does not found in %q.\n", substr, str)
}
str = "Hello! Hi! How are you?"
substr = "am"
index = strings.LastIndex(str, substr)
if index >= 0 {
fmt.Printf("Last index of %q in %q is %d.\n", substr, str, index)
} else {
fmt.Printf("%q does not found in %q.\n", substr, str)
}
}
Output:
Last index of "world" in "Hello, world!" is 7.
Last index of "l" in "Hello, world!" is 10.
Last index of "H" in "Hello! Hi! How are you?" is 11.
"am" does not found in "Hello! Hi! How are you?".
Golang strings Package Functions »