在Go字节片段中,允许您使用Split()函数分割给定的切片。此函数将字节的切片拆分为由给定分隔符分隔的所有子切片,并返回包含所有这些子切片的切片。它在bytes包下定义,因此,您必须在程序中导入bytes包才能访问Split函数。
语法:
func Split(o_slice, sep []byte) [][]byte
在这里,o_slice是字节片,sep是分隔符。如果sep为空,则它将在每个UTF-8序列之后拆分。让我们借助给出的示例来讨论这个概念:
字节切片分割示例:
//分割字节片的方法
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("Slice 1: %s", slice_1)
fmt.Printf("\nSlice 2: %s", slice_2)
fmt.Printf("\nSlice 3: %s", slice_3)
//分割字节片
//使用分割函数
res1 := bytes.Split(slice_1, []byte("eek"))
res2 := bytes.Split(slice_2, []byte(""))
res3 := bytes.Split(slice_3, []byte("%"))
//显示结果
fmt.Printf("\n\n分割后:")
fmt.Printf("\nSlice 1: %s", res1)
fmt.Printf("\nSlice 2: %s", res2)
fmt.Printf("\nSlice 3: %s", res3)
}
输出:
原始切片:
Slice 1: !!GeeksforGeeks##
Slice 2: Apple
Slice 3: %g%e%e%k%s%
分割后:
Slice 1: [!!G sforG s##]
Slice 2: [A p p l e]
Slice 3: [ g e e k s ]
分割字节切片的方法示例2:
//分割字节切片的方法
package main
import (
"bytes"
"fmt"
)
func main() {
//创建和分割
//字节片
//使用分割函数
res1 := bytes.Split([]byte("****Welcome, to, cainiaojc****"), []byte(","))
res2 := bytes.Split([]byte("Learning x how x to x trim x a x slice of bytes"), []byte("x"))
res3 := bytes.Split([]byte("cainiaojc, Geek"), []byte(""))
res4 := bytes.Split([]byte(""), []byte(","))
//显示结果
fmt.Printf("最终结果值:\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)
}
输出:
最终结果值:
Slice 1: [****Welcome to cainiaojc****]
Slice 2: [Learning how to trim a slice of bytes]
Slice 3: [n h o o o , G e e k]
Slice 4: []