How to find the last index value in slice of bytes in Golang?
Last Updated :
29 Oct, 2024
In Go, a slice is a flexible data structure that stores a variable-length sequence of elements of the same type. The LastIndex() function from the bytes package returns the last index of a specified value in a byte slice, or -1 if the value is not found.
Example
package main
import (
"bytes"
"fmt"
)
func main() {
// Define the slice of bytes
slice := []byte("GeeksforGeeks, Learning Go")
// Define the byte to search for
searchByte := []byte("e")
// Find the last index of the specified byte
lastIndex := bytes.LastIndex(slice, searchByte)
// Display the result
fmt.Printf("\n", searchByte, lastIndex)
}
Syntax
func LastIndex(ori_slice, sep_ []byte) int # Using the bytes.LastIndex Function
Using the bytes.LastIndex Function
The simplest way to find the last index of a specified byte slice is to use the LastIndex function from the bytes package.
Go
package main
import (
"bytes"
"fmt"
)
func main() {
originalSlice := []byte("Welcome to GeeksforGeeks")
searchSlice := []byte("ks")
lastIndex := bytes.LastIndex(originalSlice, searchSlice)
fmt.Printf("%s: %d\n", searchSlice, lastIndex)
}
Other method's:
Apart from the simple method mentioned above,there are few more methods which we can use to find the last index value in slice of bytes in Golang.
Manual Iteration through the Slice
You can manually iterate through the slice in reverse order to find the last index of the specified byte value.
Go
package main
import "fmt"
func lastIndexManual(slice []byte, value byte) int {
for i := len(slice) - 1; i >= 0; i-- {
if slice[i] == value {
return i
}
}
return -1
}
func main() {
slice := []byte("GeeksforGeeks")
value := byte('e')
lastIndex := lastIndexManual(slice, value)
fmt.Printf("%c: %d\n", value, lastIndex)
}
Using a Loop with bytes.Equal
You can create a custom function that checks for equality between slices to find the last index.
Example
Go
package main
import (
"bytes"
"fmt"
)
func lastIndexEqual(slice []byte, target []byte) int {
for i := len(slice) - len(target); i >= 0; i-- {
if bytes.Equal(slice[i:i+len(target)], target) {
return i
}
}
return -1
}
func main() {
slice := []byte("Geeks for Geeks")
target := []byte("for")
lastIndex := lastIndexEqual(slice, target)
fmt.Printf("%s: %d\n", target, lastIndex)
}
Using strings.LastIndex for String Conversion
Convert the byte slice to a string and use the strings.LastIndex function to find the last index.
Go
package main
import (
"fmt"
"strings"
)
func main() {
originalSlice := []byte("Geeks for Geeks")
searchString := "for"
lastIndex := strings.LastIndex(string(originalSlice), searchString)
fmt.Printf("'%s': %d\n", searchString, lastIndex)
}
Explore
Overview
Fundamentals
Control Statements
Functions & Methods
Structure
Arrays
Slices
Strings
Pointers
Concurrency