Golang 检查字节的片断是否以指定的前缀开始

Golang 检查字节的片断是否以指定的前缀开始

在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。
在Go的字节片中,你可以借助 HasPrefix ()函数来检查给定的slice是否以指定的前缀开始。如果给定的分片以指定的前缀开始,该函数返回真,如果给定的分片不以指定的前缀开始,则返回假。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程