Golang 如何找到字节片中任何元素的最后索引值
在Go语言中,slice比数组更强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储了相似类型的元素,你不允许在同一个slice中存储不同类型的元素。
在Go的字节片中,你可以使用 LastIndexAny() 函数找到给定slice中任何指定实例的最后索引值。这个函数返回任何一个Unicode代码点在原始片断中最后出现的字节索引,单位是chars。如果chars中的Unicode代码点在原始片断中不可用或为空,那么这个方法将返回-1。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问LastIndexAny函数。
语法
func LastIndexAny(ori_slice []byte, val string) int
这里,ori_slice是原始字符串,val是一个字符串,我们想找到它的最后一个索引值。让我们借助给定的例子来讨论这个概念。
例1 :
// Go program to illustrate the concept
// of the last index in the slice of bytes
package main
import (
"bytes"
"fmt"
)
func main() {
// Creating and finding the last
// index of the slice of bytes
// Using LastIndexAny function
res1 := bytes.LastIndexAny([]byte("****Welcome to GeeksforGeeks****"),
"Gjskf")
res2 := bytes.LastIndexAny([]byte("Learning how to trim a slice of bytes"),
"qoxz")
res3 := bytes.LastIndexAny([]byte("GeeksforGeeks, Geek"), "HELLO")
// Display the results
fmt.Printf("\nFinal Value:\n")
fmt.Printf("\nSlice 1: %d", res1)
fmt.Printf("\nSlice 2: %d", res2)
fmt.Printf("\nSlice 3: %d", res3)
}
输出
Final Value:
Slice 1: 27
Slice 2: 29
Slice 3: -1
例2 :
// Go program to illustrate the concept of
// the last index in the slice of bytes
package main
import (
"bytes"
"fmt"
)
func main() {
// Creating and initializing
// the slice of bytes
// Using shorthand declaration
slice_1 := []byte{'!', '!', 'G', 'e', 'e', 'k', 's', 'f',
'o', 'r', 'G', 'e', 'e', 'k', 's', '#', '#'}
slice_2 := []byte{'A', 'p', 'p', 'l', 'e'}
slice_3 := []byte{'%', 'g', 'e', 'e', 'k', 's', '%'}
// Displaying slices
fmt.Println("Original Slice:")
fmt.Printf("Slice 1: %s", slice_1)
fmt.Printf("\nSlice 2: %s", slice_2)
fmt.Printf("\nSlice 3: %s", slice_3)
// Finding the last index of
// the slice of bytes
// Using LastIndexAny function
res1 := bytes.LastIndexAny(slice_1, "eks")
res2 := bytes.LastIndexAny(slice_2, "lqzxm")
res3 := bytes.LastIndexAny(slice_3, "gOlang")
// Display the results
fmt.Printf("\n\nLast Index:\n")
fmt.Printf("\nSlice 1: %d", res1)
fmt.Printf("\nSlice 2: %d", res2)
fmt.Printf("\nSlice 3: %d", res3)
}
输出
Original Slice:
Slice 1: !!GeeksforGeeks##
Slice 2: Apple
Slice 3: %geeks%
Last Index:
Slice 1: 14
Slice 2: 3
Slice 3: 1
极客教程