📌  相关文章
📜  如何在 Golang 中分割一段字节?

📅  最后修改于: 2021-10-24 14:22:58             🧑  作者: Mango

在 Go 语言中切片比数组更强大、灵活、方便,是一种轻量级的数据结构。切片是一个可变长度的序列,用于存储相似类型的元素,不允许在同一个切片中存储不同类型的元素。
在 Go 字节切片中,您可以使用Split()函数拆分给定的切片。此函数将一个字节切片拆分为由给定分隔符分隔的所有子切片,并返回一个包含所有这些子切片的切片。它是在 bytes 包下定义的,因此您必须在程序中导入 bytes 包才能访问 Split函数。

句法:

func Split(o_slice, sep []byte) [][]byte

这里, o_slice是字节切片, sep是分隔符。如果sep为空,则它将在每个 UTF-8 序列之后拆分。让我们在给定示例的帮助下讨论这个概念:

示例 1:

// Go program to illustrate the concept
// of splitting a 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)
  
    // Splitting the slice of bytes
    // Using Split function
    res1 := bytes.Split(slice_1, []byte("eek"))
    res2 := bytes.Split(slice_2, []byte(""))
    res3 := bytes.Split(slice_3, []byte("%"))
  
    // Display the results
    fmt.Printf("\n\nAfter splitting:")
    fmt.Printf("\nSlice 1: %s", res1)
    fmt.Printf("\nSlice 2: %s", res2)
    fmt.Printf("\nSlice 3: %s", res3)
  
}

输出:

Original Slice:
Slice 1: !!GeeksforGeeks##
Slice 2: Apple
Slice 3: %g%e%e%k%s%

After splitting:
Slice 1: [!!G sforG s##]
Slice 2: [A p p l e]
Slice 3: [ g e e k s ]

示例 2:

// Go program to illustrate the concept
// of splitting a slice of bytes
package main
  
import (
    "bytes"
    "fmt"
)
  
func main() {
  
    // Creating and Splitting
    // the slice of bytes
    // Using Split function
    res1 := bytes.Split([]byte("****Welcome, to, GeeksforGeeks****"), 
                                                         []byte(","))
      
    res2 := bytes.Split([]byte("Learning x how x to x trim x a x slice of bytes"),
                                                                     []byte("x"))
      
    res3 := bytes.Split([]byte("GeeksforGeeks, Geek"), []byte(""))
      
    res4 := bytes.Split([]byte(""), []byte(","))
  
    // Display the results
    fmt.Printf("Final Value:\n")
    fmt.Printf("\nSlice 1: %s", res1)
    fmt.Printf("\nSlice 2: %s", res2)
    fmt.Printf("\nSlice 3: %s", res3)
    fmt.Printf("\nSlice 4: %s", res4)
}

输出:

Final Value:

Slice 1: [****Welcome  to  GeeksforGeeks****]
Slice 2: [Learning   how   to   trim   a   slice of bytes]
Slice 3: [G e e k s f o r G e e k s ,   G e e k]
Slice 4: []