在Go字節(jié)片段中,允許您使用Split()函數(shù)分割給定的切片。此函數(shù)將字節(jié)的切片拆分為由給定分隔符分隔的所有子切片,并返回包含所有這些子切片的切片。它在bytes包下定義,因此,您必須在程序中導(dǎo)入bytes包才能訪問(wèn)Split函數(shù)。
語(yǔ)法:
func Split(o_slice, sep []byte) [][]byte
在這里,o_slice是字節(jié)片,sep是分隔符。如果sep為空,則它將在每個(gè)UTF-8序列之后拆分。讓我們借助給出的示例來(lái)討論這個(gè)概念:
字節(jié)切片分割示例:
//分割字節(jié)片的方法
package main
import (
"bytes"
"fmt"
)
func main() {
//創(chuàng)建和初始化
//字節(jié)片
//使用簡(jiǎn)寫聲明
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)
//分割字節(jié)片
//使用分割函數(shù)
res1 := bytes.Split(slice_1, []byte("eek"))
res2 := bytes.Split(slice_2, []byte(""))
res3 := bytes.Split(slice_3, []byte("%"))
//顯示結(jié)果
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 ]
分割字節(jié)切片的方法示例2:
//分割字節(jié)切片的方法
package main
import (
"bytes"
"fmt"
)
func main() {
//創(chuàng)建和分割
//字節(jié)片
//使用分割函數(shù)
res1 := bytes.Split([]byte("****Welcome, to, nhooo****"), []byte(","))
res2 := bytes.Split([]byte("Learning x how x to x trim x a x slice of bytes"), []byte("x"))
res3 := bytes.Split([]byte("nhooo, Geek"), []byte(""))
res4 := bytes.Split([]byte(""), []byte(","))
//顯示結(jié)果
fmt.Printf("最終結(jié)果值:\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)
}輸出:
最終結(jié)果值: Slice 1: [****Welcome to nhooo****] Slice 2: [Learning how to trim a slice of bytes] Slice 3: [n h o o o , G e e k] Slice 4: []