Home »
Golang »
Golang Reference
Golang bytes.IndexFunc() Function with Examples
Golang | bytes.IndexFunc() Function: Here, we are going to learn about the IndexFunc() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 23, 2021
bytes.IndexFunc()
The IndexFunc() function is an inbuilt function of the bytes package which is used to get the byte index in the byte slice s (interpreted as a sequence of UTF-8-encoded code points) of the first Unicode code point satisfying f(c).
It accepts two parameters (s []byte, f func(r rune) bool) and returns the byte index in s of the first Unicode code point satisfying f(c), or -1 if none do.
Syntax
func IndexFunc(s []byte, f func(r rune) bool) int
Parameters
- s : The byte slice in which we have to check the value satisfying the given bool function.
- f : The bool function is used to check each byte of the byte slice (s).
Return Value
The return type of the bytes.IndexFunc() function is an int, it returns the byte index in s of the first Unicode code point satisfying f(c), or -1 if none do.
Example 1
// Golang program to demonstrate the
// example of bytes.IndexFunc() function
package main
import (
"bytes"
"fmt"
"unicode"
)
func main() {
f := func(c rune) bool {
return !unicode.IsLetter(c)
}
// Returns the index of first non-letter
fmt.Printf("%d\n", bytes.IndexFunc(
[]byte("C211, RWA Flats, Delhi65"), f))
// Returns the index of first non-letter
fmt.Printf("%d\n", bytes.IndexFunc(
[]byte("Okay@123!Hello..."), f))
}
Output:
1
4
Example 2
// Golang program to demonstrate the
// example of bytes.IndexFunc() function
package main
import (
"bytes"
"fmt"
"unicode"
)
func main() {
f1 := func(c rune) bool {
return !unicode.IsLetter(c)
}
f2 := func(c rune) bool {
return !unicode.IsNumber(c)
}
f3 := func(c rune) bool {
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
}
// Returns the index of first non-letter byte
fmt.Printf("%d\n", bytes.IndexFunc(
[]byte("C211, RWA Flats, Delhi65"), f1))
// Returns the index of first non-number byte
fmt.Printf("%d\n", bytes.IndexFunc(
[]byte("Okay@123!Hello..."), f2))
// Returns the index of first non-number & non-letter byte
fmt.Printf("%d\n", bytes.IndexFunc(
[]byte("Okay@123!Hello..."), f3))
// Returns the index of first non-number & non-letter byte
// It will return -1 because there are all letters
fmt.Printf("%d\n", bytes.IndexFunc(
[]byte("Hello"), f3))
}
Output:
1
0
4
-1
Golang bytes Package »