Golang 在指定的分隔符后分割一个字节的片断
在Go语言中,slice比数组更加强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储了相似类型的元素,你不允许在同一个slice中存储不同类型的元素。
在Go的字节片中,你可以使用 SplitN() 函数在指定的分隔符之后分割slice。这个函数将一个片断分割成给定分隔符的每个实例之后的所有子片断,并返回这些分隔符之间的子片断。如果给定的分隔符是空的,那么它就在每个UTF-8序列之后进行分割,计数表示要返回的子片的数量。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问SplitN函数。
语法
func SplitN(o_slice, sep []byte, m int) [][]byte
这里,o_slice是原始字符串,sep是分隔符,m用于查找要返回的子串的数量。在这里,如果m>0,那么它最多返回m个子片,最后一个字符串子片将不会被分割。如果 m == 0 ,那么它将返回nil。如果m<0,那么它将返回所有子片。
例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', 'G', 'e',
'e', 'k', 's', '#', '#'}
slice_2 := []byte{'A', 'p', 'p', '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 SplitN function
res1 := bytes.SplitN(slice_1, []byte("eek"), 2)
res2 := bytes.SplitN(slice_2, []byte(""), 3)
res3 := bytes.SplitN(slice_3, []byte("%"), 0)
// Display the results
fmt.Printf("\n\nAfter splitting:\n")
fmt.Printf("\nSlice 1: %s", res1)
fmt.Printf("\nSlice 2: %s", res2)
fmt.Printf("\nSlice 3: %s", res3)
}
输出
Original Slice:
Slice 1: !!GeeksforGeeksGeeks##
Slice 2: Apppple
Slice 3: %g%e%e%k%s%
After splitting:
Slice 1: [!!G sforGeeksGeeks##]
Slice 2: [A p ppple]
Slice 3: []
例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 SplitN function
res1 := bytes.SplitN([]byte("****Welcome, to, GeeksforGeeks****"),
[]byte(","), -1)
res2 := bytes.SplitN([]byte("Learning x how x to x"+
" trim x a x slice of bytes"),[]byte("x"), 3)
res3 := bytes.SplitN([]byte("Geeks,for,Geeks, Geek"), []byte(","), 0)
res4 := bytes.SplitN([]byte(""), []byte(","), 2)
// Display the results
fmt.Printf("\nFinal Result after splitting:\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 Result after splitting:
Slice 1: [****Welcome to GeeksforGeeks****]
Slice 2: [Learning how to x trim x a x slice of bytes]
Slice 3: []
Slice 4: []
极客教程