From f83f47df3a2475e2acc27991ac11a59691e60fb5 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Fri, 17 Jun 2022 17:13:58 +0800 Subject: [PATCH] feat: add SplitEx function --- strutil/string.go | 49 ++++++++++++++++++++++++++++++++++++++++++ strutil/string_test.go | 12 +++++++++++ 2 files changed, 61 insertions(+) diff --git a/strutil/string.go b/strutil/string.go index 268099d..450586b 100644 --- a/strutil/string.go +++ b/strutil/string.go @@ -248,3 +248,52 @@ func Unwrap(str string, wrapToken string) string { return str } + +// SplitEx split a given string whether the result contains empty string +func SplitEx(s, sep string, removeEmptyString bool) []string { + if sep == "" { + return []string{} + } + + n := strings.Count(s, sep) + 1 + a := make([]string, n) + n-- + i := 0 + sepSave := 0 + ignore := false + + for i < n { + m := strings.Index(s, sep) + if m < 0 { + break + } + ignore = false + if removeEmptyString { + if s[:m+sepSave] == "" { + ignore = true + } + } + if !ignore { + a[i] = s[:m+sepSave] + s = s[m+len(sep):] + i++ + } else { + s = s[m+len(sep):] + } + } + + var ret []string + if removeEmptyString { + if s != "" { + a[i] = s + ret = a[:i+1] + } else { + ret = a[:i] + } + } else { + a[i] = s + ret = a[:i+1] + } + + return ret +} diff --git a/strutil/string_test.go b/strutil/string_test.go index 16432b7..18c8714 100644 --- a/strutil/string_test.go +++ b/strutil/string_test.go @@ -177,3 +177,15 @@ func TestUnwrap(t *testing.T) { assert.Equal("***", Unwrap("***", "**")) assert.Equal("**", Unwrap("**", "**")) } + +func TestSplitEx(t *testing.T) { + assert := internal.NewAssert(t, "TestSplitEx") + + assert.Equal([]string{}, SplitEx(" a b c ", "", true)) + + assert.Equal([]string{"", "a", "b", "c", ""}, SplitEx(" a b c ", " ", false)) + assert.Equal([]string{"a", "b", "c"}, SplitEx(" a b c ", " ", true)) + + assert.Equal([]string{" a", "b", "c", ""}, SplitEx(" a = b = c = ", " = ", false)) + assert.Equal([]string{" a", "b", "c"}, SplitEx(" a = b = c = ", " = ", true)) +}