Golang 在指定的分隔符后分割分片
在Go语言中slice比数组更加强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储了相似类型的元素,你不允许在同一个slice中存储不同类型的元素。
在Go的字节slice中,你可以使用 SplitAfterN() 函数在指定的分隔符之后分割slice。这个函数在给定分隔符的每个实例之后将一个片断分割成所有子片断,并返回一个包含这些子片断的片断。如果给定的分隔符是空的,那么它就在每个UTF-8序列之后进行分割,计数表示要返回的子片的数量。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问SplitAfterN函数。
语法
func SplitAfterN(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 Splitting
// the slice of bytes
// Using SplitAfterN function
res1 := bytes.SplitAfterN([]byte("****Welcome, to, GeeksforGeeks****"),
[]byte(","), -1)
res2 := bytes.SplitAfterN([]byte("Learning x how x to x "+
"trim x a x slice of bytes"), []byte("x"), 3)
res3 := bytes.SplitAfterN([]byte("Geeks,for,Geeks, Geek"), []byte(","), 0)
res4 := bytes.SplitAfterN([]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 x how x to x trim x a x slice of bytes]
Slice 3: []
Slice 4: []
例2 :
// 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 SplitAfterN function
res1 := bytes.SplitAfterN(slice_1, []byte("eek"), 2)
res2 := bytes.SplitAfterN(slice_2, []byte(""), 3)
res3 := bytes.SplitAfterN(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: [!!Geek sforGeeksGeeks##]
Slice 2: [A p ppple]
Slice 3: []
极客教程