English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statement

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String(String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Error

Golang Miscellaneous

Go Language Slice Splitting

In Go byte fragments, you can useSplit()This function splits the given slice. This function splits the byte slice into all sub-slices separated by the given delimiter and returns a slice containing all these sub-slices. It is defined under the bytes package, so you must import the bytes package in your program to access the Split function.

Syntax:

func Split(o_slice, sep []byte) [][]byte

Here,o_sliceis a byte slicesepis a delimiter. IfsepIf it is empty, it will be split at each UTF-8Split after the sequence. Let's discuss this concept with the help of the given example:

Example of byte slice splitting:

//Method of splitting byte slices
package main
import (
    "bytes"
    "fmt"
)
func main() {
    //Creation and initialization
    //字节片
    //Use abbreviated declaration
    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: A p p l e
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, w3codebox****)), []byte(","))
    res2 := bytes.Split([]byte("Learning x how x to x trim x a x slice x of x bytes"), []byte("x"))
    res3 := bytes.Split([]byte("w3codebox, Geek
    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 w3codebox****]
Slice 2: [Learning how to trim a slice of bytes]
Slice 3: [n h o o o, G e e k]
Slice 4: []