Golang 如何分割字节切片
在Go语言中,切片比数组更强大,灵活,方便,且是一种轻量级数据结构,切片是存储相同类型元素的可变长度序列,不允许在同一切片中存储不同类型的元素。
在Go中的字节切片中,您可以使用 Split() 函数拆分给定的切片。此函数将字节切片拆分为所有由给定分隔符分隔的子切片,并返回包含所有这些子切片的切片。它在bytes package 中定义,因此您必须在程序中导入bytes package,以访问Split函数。
语法:
func Split(o_slice, sep []byte) [][]byte
在这里,o_slice 是字节切片,sep 是分隔符。如果sep为空,则会在每个UTF-8序列后拆分。让我们通过给定的示例来讨论这个概念:
示例1:
// Go程序说明如下
// 拆分字节切片的概念
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("切片1: %s", slice_1)
fmt.Printf("\n切片2: %s", slice_2)
fmt.Printf("\n切片3: %s", slice_3)
// 拆分字节切片
// 使用Split函数
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("\n切片1: %s", res1)
fmt.Printf("\n切片2: %s", res2)
fmt.Printf("\n切片3: %s", res3)
}
输出:
原始切片:
切片1: !!GeeksforGeeks##
切片2: Apple
切片3: %g%e%e%k%s%
拆分后:
切片1: [!!G sforG s##]
切片2: [A p p l e]
切片3: [ g e e k s ]
示例2:
// Go程序说明如下
// 拆分字节切片的概念
package main
import (
"bytes"
"fmt"
)
func main() {
// 创建和拆分
// 字节切片
// 使用Split函数
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(","))
// 显示结果
fmt.Printf("最终值:\n")
fmt.Printf("\n切片1: %s", res1)
fmt.Printf("\n切片2: %s", res2)
fmt.Printf("\n切片3: %s", res3)
fmt.Printf("\n切片4: %s", res4)
}
输出:
最终值:
切片1: [****Welcome to GeeksforGeeks****]
切片2: [Learning how to trim a slice of bytes]
切片3: [G e e k s f o r G e e k s , G e e k]
切片4: []