Splitting a slice of bytes after the specified separator in Golang


In Golang, it is often required to split a slice of bytes after a specific separator. This can be done using the built-in function bytes.SplitAfter(). This function splits a slice of bytes into sub-slices after each occurrence of a specified separator. In this article, we will discuss how to split a slice of bytes after a specific separator in Golang.

Syntax of bytes.SplitAfter()

The syntax of the bytes.SplitAfter() function is −

func SplitAfter(s, sep []byte) [][]byte

where s is the slice of bytes to be split, and sep is the separator.

Example

package main

import (
   "fmt"
   "bytes"
)

func main() {
   s := []byte("apple,orange,banana,mango")
   sep := []byte(",")
   result := bytes.SplitAfter(s, sep)
   fmt.Println(result)
}

Output

[[97 112 112 108 101 44] [111 114 97 110 103 101 44] [98 97 110 97 110 97 44] [109 97 110 103 111]]

In the above example, we have a slice of bytes s containing the string "apple,orange,banana,mango". We want to split this slice of bytes after each occurrence of the separator ",". We have created a separator slice sep containing the separator ",". We have passed the slice of bytes s and separator slice sep to the bytes.SplitAfter() function. The function returns a slice of byte slices result, where each byte slice contains the sub-slices of the original slice of bytes s after each occurrence of the separator ",".

Conclusion

In this article, we have discussed how to split a slice of bytes after a specific separator in Golang using the built-in function bytes.SplitAfter(). This function splits a slice of bytes into sub-slices after each occurrence of a specified separator. By using this function, we can easily split a slice of bytes into sub-slices as per our requirement.

Updated on: 18-Apr-2023

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements