Last active
June 30, 2017 19:03
-
-
Save IngCr3at1on/b48a29e10bc9b9f24690afabad802816 to your computer and use it in GitHub Desktop.
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 stringsplus | |
import ( | |
"strings" | |
) | |
// SplitX works similarly to strings.SplitN except instead of splitting into | |
// a given number of strings it splits on the given index of the split string. | |
func SplitX(s, sep string, x int) []string { | |
return splitX(s, sep, 0, x) | |
} | |
// SplitAfterX works similarly to SplitX except it will split after the separator. | |
func SplitAfterX(s, sep string, x int) []string { | |
return splitX(s, sep, len(sep), x) | |
} | |
func splitX(s, sep string, sepSave, x int) []string { | |
// Implementation is based off strings genSplit. | |
if x == 0 { | |
return nil | |
} | |
if sep == "" { | |
panic("Not implemented, see strings explode") | |
} | |
// TODO: not sure this is needed or wanted behavior lol | |
if x < 0 { | |
x = strings.Count(s, sep) + 1 | |
} | |
c := sep[0] | |
start := 0 | |
a := make([]string, 2) | |
count := 0 | |
xa := 0 | |
for i := 0; i+len(sep) <= len(s) && xa+1 < x; i++ { | |
if s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) { | |
count++ | |
if count == x { | |
a[xa] = s[start : i+sepSave] | |
xa++ | |
start = i + len(sep) | |
i += len(sep) -1 | |
} | |
} | |
} | |
a[xa] = s[start:] | |
return a[0 : xa+1] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.golang.org/p/wKohznuskN