Menu Close

Go – bytes.IndexByte() function in go

bytes.IndexByte() function is used to return the first index of byte in byte slice in go. It returns -1 if byte is not present in byte slice.

IndexByte() built-in function of bytes package or bytes.IndexByte() function takes two arguments. One argument as byte slice and another argument as byte and returns first index of byte in byte slice in go.

bytes.IndexByte() function prototype:

func IndexByte(b []byte, c byte) int

Input parameters:
b: byte slice
c: byte to be searched in byte slice b

Return:
It returns first index of byte "c" in byte slice "b" in go

Explanation:

1)
s := []byte("John is doing well")
c := byte('i')

Output: 5, since byte 'i' is present at the 5th index in s byte slice "John is doing well".

2)
s := []byte("John is doing well")
c := []byte('z')

Output: -1, since byte 'z' is not present at any index in s byte slice "John is doing well".

3)
s := []byte{10, 20, 30}
c := byte(20)

Output: 1, since byte '20' is present at the 1st index in s byte slice "{10, 20, 30}".

4)
s := []byte("去是伟大的!")
c := byte('!')

Output: 15, since byte '!' is present at the 15th index in s byte slice "去是伟大的!".

5)
s := []byte("hello world")
c := byte(' ')

Output: 5 , since empty byte ' ' is present at the 5th index in s byte slice "hello world"

Example:

package main

import (
	"bytes"
	"fmt"
)

// main function
func main() {
    
    s := []byte("John is doing well")
    c := byte('i')
    
	fmt.Println(bytes.IndexByte(s, c))
	
	
    s = []byte("John is doing well")
    c = byte('z')
    
    fmt.Println(bytes.IndexByte(s, c))
    
	
    s = []byte{10, 20, 30}
    c = byte(20)

	fmt.Println(bytes.IndexByte(s, c))
	

	s = []byte("去是伟大的!")
    c = byte('!')
	
	fmt.Println(bytes.IndexByte(s, c))
	
	
	s = []byte("hello world")
    c = byte(' ')
    
    fmt.Println(bytes.IndexByte(s, c))
}

Output:

5
-1
1
15
5

To learn more about golang, Please refer given below link:

References:

https://golang.org/doc/

Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published.

Contact Us