📌  相关文章
📜  检查字节片是否以 Golang 中的指定前缀开头

📅  最后修改于: 2021-10-25 02:31:35             🧑  作者: Mango

在 Go 语言中切片比数组更强大、灵活、方便,是一种轻量级的数据结构。切片是一个可变长度的序列,用于存储相似类型的元素,不允许在同一个切片中存储不同类型的元素。
在 Go 字节切片中,您可以借助HasPrefix ()函数检查给定的切片是否以指定的前缀开头。如果给定的切片以指定的前缀开头,则此函数返回 true,如果给定的切片不以指定的前缀开头,则返回 false。它是在 bytes 包下定义的,因此您必须在程序中导入 bytes 包才能访问 HasPrefix函数。

句法:

func HasPrefix(slice_1, pre []byte) bool

这里, slice_1是原始字节片,pre 是前缀,也是字节片。此函数的返回类型为 bool 类型。让我们借助一个例子来讨论这个概念:

例子:

// Go program to illustrate how to check the
// given slice starts with the specified prefix
package main
  
import (
    "bytes"
    "fmt"
)
  
func main() {
  
    // Creating and initializing
    // 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'}
  
    // Checking whether the given slice starts 
    // with the specified prefix or not
    // Using  HasPrefix () function
    res1 := bytes.HasPrefix(slice_1, []byte("G"))
    res2 := bytes.HasPrefix(slice_2, []byte("O"))
    res3 := bytes.HasPrefix([]byte("Hello! I am Apple."), []byte("Hello"))
    res4 := bytes.HasPrefix([]byte("Hello! I am Apple."), []byte("Welcome"))
    res5 := bytes.HasPrefix([]byte("Hello! I am Apple."), []byte("H"))
    res6 := bytes.HasPrefix([]byte("Hello! I am Apple."), []byte("X"))
    res7 := bytes.HasPrefix([]byte("Geeks"), []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)
    fmt.Println("Result_6: ", res6)
    fmt.Println("Result_7: ", res7)
  
}

输出:

Result_1:  true
Result_2:  false
Result_3:  true
Result_4:  false
Result_5:  true
Result_6:  false
Result_7:  true