
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Last Index Value of Element in Slice of Bytes in Golang
In Go, finding the last index value of an element in a slice of bytes can be a common requirement while working with strings and byte arrays. Fortunately, there is a built-in function in Go that allows us to find the last index value of an element in a slice of bytes.
In this article, we will discuss how to find the last index value of any element in a slice of bytes in Go.
Syntax of LastIndexByte Function
The built-in function LastIndexByte returns the index of the last occurrence of the given byte c in the slice of bytes s, or -1 if c is not present in s.
func LastIndexByte(s []byte, c byte) int
Example of Using LastIndexByte Function
Let's see how we can use the LastIndexByte function to find the last index value of an element in a slice of bytes.
package main import ( "bytes" "fmt" ) func main() { s := []byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'} c := byte('f') lastIndex := bytes.LastIndexByte(s, c) fmt.Printf("The last index of '%c' in %v is %d\n", c, s, lastIndex) }
Output
The last index of 'f' in [97 98 99 100 101 102 103 104 105 106] is 5
In the above example, we have a slice of bytes s that contains the values from 'a' to 'j'. We want to find the last index value of the byte 'f' in the slice of bytes s.
To do that, we pass the slice of bytes s and the byte 'f' as arguments to the LastIndexByte function. The function returns the index of the last occurrence of the byte 'f' in the slice of bytes s.
Finally, we print the last index value of the byte 'f' in the slice of bytes s.
Conclusion
In this article, we discussed how to find the last index value of any element in a slice of bytes in Go using the built-in LastIndexByte function. By using this function, we can easily find the last occurrence of a specific byte in a byte array.