Created
June 17, 2020 08:13
-
-
Save nexus166/8081f477aa0c9a20e5c7f0574c5e207f to your computer and use it in GitHub Desktop.
split and merge []byte in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.golang.org/p/XnRN91uavnE