Menu Close

Go – Find sub-byte slice in byte slice from last in go

bytes.LastIndex() function is used to find sub-byte slice in byte slice from last in go. It returns the index of sub-byte slice from last.

LastIndex() built-in function of bytes package returns the last instance of sub-byte slice in byte slice. It returns -1 if sub-byte slice is not present in byte slice.

bytes.LastIndex() function prototype:

func LastIndex(s, sep []byte) int

or 

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

Input parameters:
s: byte slices
sep: byte slice to be searched in s from last.

Return:
It returns index of sep byte slice in byte slice s from last.

Explanation on find sub-byte slice in byte slice from last in go

1)
s := []byte("He is all well and well")
sep := []byte("well")

Output: 19

2)
s = []byte("He is all well and well")
sep = []byte("yoo")

Output: -1

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

Output: 5

Example:

package main

import (
	"bytes"
	"fmt"
)

// main function
func main() {
    
    s := []byte("He is all well and well")
    sep := []byte("well")
    
	fmt.Println(bytes.LastIndex(s, sep))
	
	
    s = []byte("He is all well and well")
    sep = []byte("yoo")
    
    fmt.Println(bytes.LastIndex(s, sep))
    
    
	s = []byte{10, 20, 30, 20, 30, 20, 40}
    sep = []byte{20}
    
    fmt.Println(bytes.LastIndex(s, sep))
}

Output:

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