Home »
Golang »
Golang Reference
Golang strings.LastIndexFunc() Function with Examples
Golang | strings.LastIndexFunc() Function: Here, we are going to learn about the LastIndexFunc() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 19, 2021
strings.LastIndexFunc()
The LastIndexFunc() function is an inbuilt function of strings package which is used to get the index of the last Unicode code point satisfying the function in respect to the character of the string. It accepts two parameters – string and a function. And, returns the last index, or -1 if any character of the string does not satisfy the function.
Syntax
func LastIndexFunc(str string, f func(rune) bool) int
Parameters
- str : String in which we have to check the last index of the character through the function.
- f : Function that contains the condition.
Return Value
The return type of the LastIndexFunc() function is an int, it returns the index of the last Unicode code point satisfying the function in respect to the character of the string, or -1 if any character of the string does not satisfy the function.
Example 1
// Golang program to demonstrate the
// example of strings.LastIndexFunc() Function
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
// function to check character
// is in lowercase or not
f := func(c rune) bool {
return unicode.IsLower(c)
}
fmt.Println(strings.LastIndexFunc("HELLO, World!", f))
fmt.Println(strings.LastIndexFunc("HELLO, WORLD!", f))
}
Output:
11
-1
Example 2
// Golang program to demonstrate the
// example of strings.LastIndexFunc() Function
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
var str string
// function to check character
// is in lowercase or not
fLower := func(c rune) bool {
return unicode.IsLower(c)
}
// function to check character
// is in uppercase or not
fUpper := func(c rune) bool {
return unicode.IsUpper(c)
}
// function to check character
// is a digist or not
fDigit := func(c rune) bool {
return unicode.IsDigit(c)
}
str = "Hello, World!"
fmt.Println("Last Lowercase Character's Index:", strings.LastIndexFunc(str, fLower))
fmt.Println("Last Uppercase Character's Index:", strings.LastIndexFunc(str, fUpper))
fmt.Println("Last Digit's Index:", strings.LastIndexFunc(str, fDigit))
str = "Okay@123!"
fmt.Println("Last Lowercase Character's Index:", strings.LastIndexFunc(str, fLower))
fmt.Println("Last Uppercase Character's Index:", strings.LastIndexFunc(str, fUpper))
fmt.Println("Last Digit's Index:", strings.LastIndexFunc(str, fDigit))
}
Output:
Last Lowercase Character's Index: 11
Last Uppercase Character's Index: 7
Last Digit's Index: -1
Last Lowercase Character's Index: 3
Last Uppercase Character's Index: 0
Last Digit's Index: 7
Golang strings Package Functions »