From 7dfd3d17ef4cc85cbcd3055e4d2ff4ec8be181a5 Mon Sep 17 00:00:00 2001 From: seekwe Date: Wed, 25 Dec 2024 18:30:09 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20refactor:=20Update=20Slice=20fun?= =?UTF-8?q?ction=20to=20accept=20custom=20separator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zarray/string.go | 20 ++++++++++++++------ zarray/string_test.go | 10 +++++----- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/zarray/string.go b/zarray/string.go index 63b6f6d..c137033 100644 --- a/zarray/string.go +++ b/zarray/string.go @@ -11,28 +11,36 @@ import ( ) // Slice converts a string to a slice. -// If n is not empty, the string will be split into n parts. -func Slice[T comparable](s string, n ...int) []T { +// If value is not empty, the string will be split into value parts. +func Slice[T comparable](s, sep string, n ...int) []T { if s == "" { return []T{} } var ss []string if len(n) > 0 { - ss = strings.SplitN(s, ",", n[0]) + ss = strings.SplitN(s, sep, n[0]) } else { - ss = strings.Split(s, ",") + ss = strings.Split(s, sep) } res := make([]T, len(ss)) + ni := make([]uint32, 0, len(ss)) for i := range ss { - ztype.To(zstring.TrimSpace(ss[i]), &res[i]) + if v := zstring.TrimSpace(ss[i]); v != "" { + ztype.To(v, &res[i]) + } else { + ni = append(ni, uint32(i)) + } } + for i := range ni { + res = append(res[:ni[i]], res[ni[i]+1:]...) + } return res } // Join slice to string. -// If n is not empty, the string will be split into n parts. +// If value is not empty, the string will be split into value parts. func Join[T comparable](s []T, sep string) string { if len(s) == 0 { return "" diff --git a/zarray/string_test.go b/zarray/string_test.go index 4867366..9772bf7 100644 --- a/zarray/string_test.go +++ b/zarray/string_test.go @@ -12,11 +12,11 @@ import ( func TestSlice(t *testing.T) { tt := zlsgo.NewTest(t) - tt.Equal([]string{"a", "b", "c"}, zarray.Slice[string]("a,b,c")) - tt.Equal([]int{1, 2, 3}, zarray.Slice[int]("1,2,3")) - tt.Equal([]float64{1.1, 2.2, 3.3}, zarray.Slice[float64]("1.1,2.2,3.3")) - tt.Equal([]string{"1.1", "2.2,3.3"}, zarray.Slice[string]("1.1,2.2,3.3", 2)) - tt.Equal([]int{}, zarray.Slice[int]("")) + tt.Equal([]string{"a", "b", "c"}, zarray.Slice[string]("a,b,c", ",")) + tt.Equal([]int{1, 2, 3}, zarray.Slice[int]("1,2,3", ",")) + tt.Equal([]float64{1.1, 2.2, 3.3}, zarray.Slice[float64]("1.1,2.2,3.3", ",")) + tt.Equal([]string{"1.1", "2.2,3.3"}, zarray.Slice[string]("1.1,2.2,3.3", ",", 2)) + tt.Equal([]int{}, zarray.Slice[int]("", ",")) } func TestJoin(t *testing.T) {