Home »
Golang »
Golang Reference
Golang bytes.IndexAny() Function with Examples
Golang | bytes.IndexAny() Function: Here, we are going to learn about the IndexAny() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 23, 2021
bytes.IndexAny()
The IndexAny() function is an inbuilt function of the bytes package which is used to get the byte index of the first occurrence in the given byte slice s (interpreted s as a sequence of UTF-8-encoded Unicode code points) of any of the Unicode code points in chars. It returns -1 if chars are empty or if there is no code point in common.
It accepts two parameters (s []byte, chars string) and returns the byte index of the first occurrence in s of any of the Unicode code points in chars.
Syntax
func IndexAny(s []byte, chars string) int
Parameters
- s : The byte slice in which we have to check any character from the string chars.
- chars : The string whose characters (any) are to be checked within the s.
Return Value
The return type of the bytes.IndexAny() function is an int, it returns the byte index of the first occurrence in s of any of the Unicode code points in chars.
Example 1
// Golang program to demonstrate the
// example of bytes.IndexAny() function
package main
import (
"bytes"
"fmt"
)
func main() {
str := "Hello, world!"
fmt.Println(bytes.IndexAny([]byte(str), "Hello"))
fmt.Println(bytes.IndexAny([]byte(str), "l"))
fmt.Println(bytes.IndexAny([]byte(str), "Hi"))
fmt.Println(bytes.IndexAny([]byte(str), "xw"))
fmt.Println(bytes.IndexAny([]byte(str), "y"))
}
Output:
0
2
0
7
-1
Example 2
// Golang program to demonstrate the
// example of bytes.IndexAny() function
package main
import (
"bytes"
"fmt"
)
func main() {
var str string
var sep string
str = "Hi there!"
sep = "!"
result := bytes.IndexAny([]byte(str), sep)
if result != -1 {
fmt.Printf("Any chars of %q found at the IndexAny %d in %q\n",
sep, result, str)
} else {
fmt.Printf("Any chars of %q doest not found in %q\n",
sep, str)
}
str = "Aspire to inspire before we expire."
sep = "expire."
result = bytes.IndexAny([]byte(str), sep)
if result != -1 {
fmt.Printf("Any chars of %q found at the IndexAny %d in %q\n",
sep, result, str)
} else {
fmt.Printf("Any chars of %q doest not found in %q\n",
sep, str)
}
str = "Aspire to inspire before we expire."
sep = "yz"
result = bytes.IndexAny([]byte(str), sep)
if result != -1 {
fmt.Printf("Any chars of %q found at the IndexAny %d in %q\n",
sep, result, str)
} else {
fmt.Printf("Any chars of %q doest not found in %q\n",
sep, str)
}
}
Output:
Any chars of "!" found at the IndexAny 8 in "Hi there!"
Any chars of "expire." found at the IndexAny 2 in "Aspire to inspire before we expire."
Any chars of "yz" doest not found in "Aspire to inspire before we expire."
Golang bytes Package »