Menu Close

Go – bytes.Index() function in go

bytes.Index() function is used to return the index of first sub-byte slice in another byte slice in go.

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

bytes.Index() function prototype:

func Index(s, sep []byte) int

or

func Index(s []byte, sep []byte) int

Input parameters:
s: byte slice
sep: first byte slice to be searched in byte slice s

Return:
It returns first index of sub-byte slice "sep" in another byte slice "s" in go

Explanation:

1)
s := []byte("John is doing well")
sep := []byte("is")

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

2)
s := []byte("John is doing well")
sep := []byte("runi")

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

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

Output: 1, since sep sub-slice "{20, 30}" is present at the 1th index in s byte slice "{10, 20, 30}".

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

Output: 0, since sep sub-slice "去是伟大的!" is present at the 0th index in s byte slice "去是伟大的!".

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

Output: 0 , since sep sub-slice "" is empty then It returns 0.

Example:

package main

import (
	"bytes"
	"fmt"
)

// main function
func main() {
    
    s := []byte("John is doing well")
    sep := []byte("is")
    
	fmt.Println(bytes.Index(s, sep))
	
	
    s = []byte("John is doing well")
    sep = []byte("runi")
    
    fmt.Println(bytes.Index(s, sep))
    
	
    s = []byte{10, 20, 30}
    sep = []byte{20, 30}

	fmt.Println(bytes.Index(s, sep))
	

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

Output:

5
-1
1
0
0

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. Required fields are marked *