strings.LastIndexAny() Function in Golang With Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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"))
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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, " "))
}

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.