VOOZH about

URL: https://www.geeksforgeeks.org/go-language/how-to-split-a-slice-of-bytes-in-golang/

⇱ How to split a slice of bytes in Golang? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to split a slice of bytes in Golang?

Last Updated : 12 Nov, 2024

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.

Example

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))
}
}

Syntax

bytes.Split(slice, separator)

Using bytes.Split

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.

Syntax

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


Output
Split:
a
b
c

Splitting with a Different Delimiter

You can use any byte slice as the separator. Here’s the same example using a semicolon (;) as the delimiter.

Example


Output
Split using';':
a
b
c

Handling No Separator Found

If the separator is not found in the slice, the function will return a slice containing only the original byte slice.


Output
Split parts with non-existent separator '|':
a,b,c

Splitting by Each Character (Empty Separator)

Using an empty byte slice ([]byte{}) as the separator splits the slice into individual bytes.


Output
Split each character:
a
b
c

Conclusion

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.


Comment
Article Tags:

Explore