Golang 如何在字节切片中找到任何元素的索引值
在Go语言中,切片比数组更强大、灵活、方便,是一种轻量级的数据结构。切片是一种变长序列,可以存储相同类型的元素,不允许在同一切片中存储不同类型的元素。
在Go的字节切片中,您可以使用 IndexAny() 函数找到给定切片中任何指定实例的第一个索引值。该函数返回原始切片中任何Unicode代码点中chars的第一个出现的字节索引。如果原始切片中不存在来自chars的Unicode代码点或为空,则此方法将返回-1。它在bytes包下定义,因此您必须在程序中导入bytes包以访问IndexAny函数。
语法:
func IndexAny(ori_slice []byte, val string) int
这里,ori_slice是原始字符串,val是要查找第一个索引值的字符串。让我们通过给定的示例来讨论此概念:
示例1:
// Go程序演示了字节片的索引概念
package main
import (
"bytes"
"fmt"
)
func main() {
//创建和查找字节片的索引
//使用IndexAny函数
res1 := bytes.IndexAny([]byte("****Welcome to GeeksforGeeks****"),
"Gjskf")
res2 := bytes.IndexAny([]byte("Learning how to trim a slice of bytes"),
"qoxz")
res3 := bytes.IndexAny([]byte("GeeksforGeeks, Geek"),
"HELLO")
//显示结果
fmt.Printf("\n\n最终值:\n")
fmt.Printf("\n切片1:%d", res1)
fmt.Printf("\n切片2:%d", res2)
fmt.Printf("\n切片3:%d", res3)
}
输出:
最终值:
切片1:15
切片2:10
切片3:-1
示例2:
// Go程序演示了字节片的索引概念
package main
import (
"bytes"
"fmt"
)
func main() {
// 使用简写声明创建和初始化字节片
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', '%'}
//显示切片
fmt.Println("原始字节片:")
fmt.Printf("切片1:%s", slice_1)
fmt.Printf("\n切片2:%s", slice_2)
fmt.Printf("\n切片3:%s", slice_3)
// 使用IndexAny函数找到字节片的索引
res1 := bytes.IndexAny(slice_1, "eks")
res2 := bytes.IndexAny(slice_2, "lqzxm")
res3 := bytes.IndexAny(slice_3, "xxxxx")
//显示结果
fmt.Printf("\n\n最后索引:\n")
fmt.Printf("\n切片1:%d", res1)
fmt.Printf("\n切片2:%d", res2)
fmt.Printf("\n切片3:%d", res3)
}
输出:
原始字节片:
切片1:!!GeeksforGeeks##
切片2:Apple
切片3:%geeks%
最后索引:
切片1:3
切片2:3
切片3:-1
极客教程