The IndexFunc function is used to find the index of the first appearance of a Unicode code character in a string, such that it satisfies the provided function.
To use this function, we must import the strings package in our file and access the IndexFunc function within it, using the . notation (string.IndexFunc).
Here is the definition of the IndexFunc function:
func IndexFunc (str string, fun func(rune) bool) int
The IndexFunc function takes two arguments:
str: This is an argument of type string. It represents the list of characters that we want to search.
fun: This argument represents the function that takes a rune as an argument and returns a boolean variable.
The IndexFunc function returns the index where it finds the first instance of a character that the function fun returns True on. If there is no such character in the whole string, then -1 is returned.
In the code given below, we use the IndexFunc function to find the position of the first Greek letter that appears in a string:
package mainimport ("fmt""strings""unicode")func main() {fun := func(r rune) bool {return unicode.Is(unicode.Greek, r)}str := "The greek letter α is used often in mathematics"x := strings.IndexFunc(str, fun)fmt.Println("a greek alphabet appears at position: ", x)}
Note: The
unicodepackage is imported here, so that we can use theunicode.Isfunction. This function checks if a certainrunevalue is present in a list of Unicode values. In this case, the list consists of all Greek characters, which we get by usingunicode.Greek.
The following example demonstrates a case where no character in the string satisfies the given function:
package mainimport ("fmt""strings""unicode")func main() {fun := func(r rune) bool {return unicode.Is(unicode.Greek, r)}str := "Educative Inc."x:= strings.IndexFunc(str, fun)if x == -1{fmt.Println("could not find any greek alphabets in : \"",str, "\"" )}}