![]() |
VOOZH | about |
In Golang, you can split a slice of bytes into multiple parts using the bytes.Split function. This is useful when dealing with data like encoded strings, file contents, or byte streams that must be divided by a specific delimiter.
package main
import (
"bytes"
"fmt"
)
func main() {
// Initial byte slice
data := []byte("a,b,c")
// Splitting the byte slice
parts := bytes.Split(data, []byte(","))
fmt.Println("Split parts:")
for _, part := range parts {
fmt.Println(string(part))
}
}
bytes.Split(slice, separator)
Table of Content
The bytes.Split function in Golang lets you break a slice of bytes into parts using a specific separator, making it helpful for handling data like encoded text, file contents, or byte streams.
bytes.Split(slice, separator)
slice: The original slice of bytes to be split.separator: The delimiter that indicates where to split the slice.This function returns a slice of byte slices, where each element is a segment from the original slice split by the separator.
Example
Split: a b c
You can use any byte slice as the separator. Here’s the same example using a semicolon (;) as the delimiter.
Example
Split using';': a b c
If the separator is not found in the slice, the function will return a slice containing only the original byte slice.
Split parts with non-existent separator '|': a,b,c
Using an empty byte slice ([]byte{}) as the separator splits the slice into individual bytes.
Split each character: a b c
The bytes.Split function in Go is a powerful tool for dividing byte slices using custom delimiters, offering flexibility when working with raw byte data.