Home »
Golang »
Golang Reference
Golang bytes.IndexByte() Function with Examples
Golang | bytes.IndexByte() Function: Here, we are going to learn about the IndexByte() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 23, 2021
bytes.IndexByte()
The IndexByte() function is an inbuilt function of the bytes package which is used to get the index of the first instance of the byte c in the byte slice b.
It accepts two parameters (b []byte, c byte) and returns the index of the first instance of c in b, or -1 if c is not present in b.
Syntax
func IndexByte(b []byte, c byte) int
Parameters
- b : The byte slice in which we have to check the byte.
- c : The byte value whose index of the first instance in the byte slice (b) is to be found.
Return Value
The return type of the bytes.IndexByte() function is an int, it returns the index of the first instance of c in b, or -1 if c is not present in b.
Example 1
// Golang program to demonstrate the
// example of bytes.IndexByte() function
package main
import (
"bytes"
"fmt"
)
func main() {
str := "Hello, world!"
fmt.Println(bytes.IndexByte([]byte(str), 'H'))
fmt.Println(bytes.IndexByte([]byte(str), 'l'))
fmt.Println(bytes.IndexByte([]byte(str), 'e'))
fmt.Println(bytes.IndexByte([]byte(str), 'x'))
fmt.Println(bytes.IndexByte([]byte(str), 'y'))
}
Output:
0
2
1
-1
-1
Example 2
// Golang program to demonstrate the
// example of bytes.IndexByte() function
package main
import (
"bytes"
"fmt"
)
func main() {
var str string
var c byte
str = "Hi there!"
c = '!'
result := bytes.IndexByte([]byte(str), c)
if result != -1 {
fmt.Printf("%c found at the IndexByte %d in %q\n",
c, result, str)
} else {
fmt.Printf("%c doest not found in %q\n",
c, str)
}
str = "Aspire to inspire before we expire."
c = 't'
result = bytes.IndexByte([]byte(str), c)
if result != -1 {
fmt.Printf("%c found at the IndexByte %d in %q\n",
c, result, str)
} else {
fmt.Printf("%c doest not found in %q\n",
c, str)
}
str = "Aspire to inspire before we expire."
c = 'z'
result = bytes.IndexByte([]byte(str), c)
if result != -1 {
fmt.Printf("%c found at the IndexByte %d in %q\n",
c, result, str)
} else {
fmt.Printf("%c doest not found in %q\n",
c, str)
}
}
Output:
! found at the IndexByte 8 in "Hi there!"
t found at the IndexByte 7 in "Aspire to inspire before we expire."
z doest not found in "Aspire to inspire before we expire."
Golang bytes Package »