Skip to content

Instantly share code, notes, and snippets.

@xinau
Last active May 22, 2020 12:04
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 xinau/f73c7e7ac06032b5e12d25b140aa9e68 to your computer and use it in GitHub Desktop.
Save xinau/f73c7e7ac06032b5e12d25b140aa9e68 to your computer and use it in GitHub Desktop.
CountFunc and SplitNFunc for byte arrays in golang
package main
import (
"bytes"
"fmt"
)
func CountFunc(s []byte, f func(rune) bool) int {
n := 0
for i := 0; i < len(s); i++ {
if f(rune(s[i])) {
n++
}
}
return n
}
func SplitNFunc(s []byte, f func(rune) bool, n int) [][]byte {
if n == 0 {
return nil
}
if n < 0 {
n = CountFunc(s, f) + 1
}
arr := make([][]byte, n)
n--
i := 0
for i < n {
m := bytes.IndexFunc(s, f)
if m < 0 {
break
}
arr[i] = s[: m+1 : m+1]
s = s[m+1:]
i++
}
arr[i] = s
return arr[:i+1]
}
func main() {
f := func (r rune) bool {
return '0' <= r && r <= '9'
}
fmt.Printf("%q\n", SplitNFunc([]byte("a1b2c3d"), f, -1))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment