Skip to content

Instantly share code, notes, and snippets.

@nexus166
Created June 17, 2020 08:13
Show Gist options
  • Save nexus166/8081f477aa0c9a20e5c7f0574c5e207f to your computer and use it in GitHub Desktop.
Save nexus166/8081f477aa0c9a20e5c7f0574c5e207f to your computer and use it in GitHub Desktop.
split and merge []byte in go
package main
import (
"fmt"
)
func main() {
s := "He turned in the research paper on Friday; otherwise, he would have not passed the class."
fmt.Printf("%s\nlenght:%d\n", s, len(s))
chunked := chunk([]byte(s), 3)
fmt.Printf("%s\nlenght:%d\n", chunked, len(chunked))
merged := merge(chunked)
fmt.Printf("%s\nlenght:%d\n", merged, len(merged))
}
func chunk(b []byte, size int) (bb [][]byte) {
for len(b) > 0 {
if len(b) < size {
size = len(b)
}
bb, b = append(bb, b[:size]), b[size:]
}
return
}
func merge(bb [][]byte) (b []byte) {
switch len(bb) {
case 0:
case 1:
return bb[0]
default:
for i := range bb {
b = append(b, bb[i]...)
}
}
return
}
@nexus166
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment