Open In App

strings.LastIndexAny() Function in Golang With Examples

Improve
Improve
Like Article
Like
Save
Share
Report

strings.LastIndexAny() Function in the Golang is used to find the index of the last instance of any Unicode code point from chars in a given string. If the Unicode code point from chars 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 LastIndexAny(str, chars string) int

Here, str is the original string and charstr is a Unicode code point from chars whose we want to find the last index value.

Example 1:




// Golang program to illustrate the
// strings.LastIndexAny() Function
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    // taking a string
    str := "GeeksforGeeks"
  
    // using the function
    fmt.Println(strings.LastIndexAny(str, "Ge"))
    fmt.Println(strings.LastIndexAny(str, "g"))
    fmt.Println(strings.LastIndexAny(str, "sf"))
}


Output:

10
-1
12

For the second output, character ‘g’ is not present so it displays -1 as a result. Note here that this function is case sensitive so it takes ‘G’ and ‘g’ differently.

Example 2:




// Golang program to illustrate the
// strings.LastIndexAny() Function
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    // taking a string
    str := "New Delhi, India"
  
    // using the function
    fmt.Println(strings.LastIndexAny(str, "Ii"))
    fmt.Println(strings.LastIndexAny(str, " "))
}


Output:

14
10

For the first output the characters are ‘I’ and ‘i’. So the compiler will display the index of the last occurrence of either ‘I’ or ‘i’ and since ‘i’ comes last here so that will be the output. For the second output, the character to be searched is a space. Since there are two spaces in the given string so the output will be the index of the last space.



Last Updated : 19 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads