Golang 检查指定的元素是否存在于字节的片断中
在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储了相似类型的元素,你不允许在同一个slice中存储不同类型的元素。在Go的字节片中,你可以使用下面的函数检查给定的片子是否包含指定的元素。这些函数是在字节包下定义的,因此,你必须在你的程序中导入字节包来访问这些函数。
1.包含: 该函数用于检查指定的元素是否存在于给定的字节片中。如果该元素存在于片断中,则该方法返回true;如果该元素不存在于给定的片断中,则返回false。
语法
func Contains(slice_1, sub_slice []byte) bool
例子
// Go program to illustrate how to check the
// slice contains the specified element in it
package main
import (
"bytes"
"fmt"
)
func main() {
// Creating and initializing
// slice of bytes
// Using shorthand declaration
slice_1 := []byte{'A', 'N', 'M',
'O', 'P', 'Q'}
// Checking the slice
// using Contains function
res1 := bytes.Contains(slice_1, []byte{'A'})
res2 := bytes.Contains(slice_1, []byte{'x'})
res3 := bytes.Contains([]byte("GeeksforGeeks"), []byte("ks"))
res4 := bytes.Contains([]byte("Geeks"), []byte(""))
res5 := bytes.Contains([]byte(""), []byte(""))
// Displaying results
fmt.Println("Result 1:", res1)
fmt.Println("Result 2:", res2)
fmt.Println("Result 3:", res3)
fmt.Println("Result 4:", res4)
fmt.Println("Result 5:", res5)
}
输出
Result 1: true
Result 2: false
Result 3: true
Result 4: true
Result 5: true
2.ContainsAny: 这个函数用来检查在给定的字节片中是否有任何一个字符的UTF-8编码的代码点存在。如果字符中的任何一个UTF-8编码的代码点存在于该片断中,则该方法返回true;如果字符中的任何一个UTF-8编码的代码点不存在于给定的片断中,则返回false。
语法
func ContainsAny(slice_1 []byte, charstr string) bool
例子
// Go program to illustrate how to check the
// slice contain the specified string in it
package main
import (
"bytes"
"fmt"
)
func main() {
// Creating and initializing
// slice of bytes
// Using shorthand declaration
slice_1 := []byte{'A', 'N', 'M', 'O', 'P', 'Q'}
// Checking the slice
// Using ContainsAny function
res1 := bytes.ContainsAny(slice_1, "A")
res2 := bytes.ContainsAny(slice_1, "a")
res3 := bytes.ContainsAny([]byte("GeeksforGeeks"), "ksjkd")
res4 := bytes.ContainsAny([]byte("Geeks"), "")
res5 := bytes.ContainsAny([]byte(""), "")
// Displaying results
fmt.Println("Result 1:", res1)
fmt.Println("Result 2:", res2)
fmt.Println("Result 3:", res3)
fmt.Println("Result 4:", res4)
fmt.Println("Result 5:", res5)
}
输出
Result 1: true
Result 2: false
Result 3: true
Result 4: false
Result 5: false
极客教程