Last active
May 22, 2020 12:04
-
-
Save xinau/f73c7e7ac06032b5e12d25b140aa9e68 to your computer and use it in GitHub Desktop.
CountFunc and SplitNFunc for byte arrays in golang
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 ( | |
"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