Skip to content

Instantly share code, notes, and snippets.

@taliesinb
Created May 29, 2012 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taliesinb/2821937 to your computer and use it in GitHub Desktop.
Save taliesinb/2821937 to your computer and use it in GitHub Desktop.
Some implementations of SplitByte
package split
import "bytes"
func CountByte(s []byte, c byte) int {
count := 0
i := 0
for i < len(s) {
if s[i] != c {
o := bytes.IndexByte(s[i:], c)
if o < 0 {
break
}
i += o
}
count++
i++
continue
}
return count
}
func SplitByte1(str []byte, sep byte) [][]byte {
start := 0
na := 0
n := CountByte(str, sep) + 1
a := make([][]byte, n)
for i := 0; i < len(str) && na+1 < n; i++ {
if str[i] == sep {
a[na] = str[start : i]
na++
start = i + 1
}
}
a[na] = str[start:]
return a[0 : na+1]
}
func SplitByte2(s []byte, sep byte) [][]byte {
sep2 := []byte{sep};
return genSplit(s, sep2, 0, -1)
}
func genSplit(s, sep []byte, sepSave, n int) [][]byte {
if n == 0 {
return nil
}
if n < 0 {
n = bytes.Count(s, sep) + 1
}
c := sep[0]
start := 0
a := make([][]byte, n)
na := 0
for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ {
if s[i] == c && (len(sep) == 1 || bytes.Equal(s[i:i+len(sep)], sep)) {
a[na] = s[start : i+sepSave]
na++
start = i + len(sep)
i += len(sep) - 1
}
}
a[na] = s[start:]
return a[0 : na+1]
}
func SplitByte3(s []byte, sep byte) [][]byte {
sep2 := []byte{sep};
return bytes.Split(s, sep2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment