From 898216d419ad046ee3c3dee91df851e4e30461d7 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 29 Mar 2018 12:04:01 +0200 Subject: [PATCH] add SplitAndTrim func (#183) Refs https://github.com/tendermint/tendermint/issues/1380 --- common/string.go | 17 +++++++++++++++++ common/string_test.go | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/common/string.go b/common/string.go index ae140c9f4..dfa262d3f 100644 --- a/common/string.go +++ b/common/string.go @@ -41,3 +41,20 @@ func StringInSlice(a string, list []string) bool { } return false } + +// SplitAndTrim slices s into all subslices separated by sep and returns a +// slice of the string s with all leading and trailing Unicode code points +// contained in cutset removed. If sep is empty, SplitAndTrim splits after each +// UTF-8 sequence. First part is equivalent to strings.SplitN with a count of +// -1. +func SplitAndTrim(s, sep, cutset string) []string { + if s == "" { + return []string{} + } + + spl := strings.Split(s, sep) + for i := 0; i < len(spl); i++ { + spl[i] = strings.Trim(spl[i], cutset) + } + return spl +} diff --git a/common/string_test.go b/common/string_test.go index b8a917c16..82ba67844 100644 --- a/common/string_test.go +++ b/common/string_test.go @@ -30,3 +30,22 @@ func TestIsHex(t *testing.T) { assert.True(t, IsHex(v), "%q is hex", v) } } + +func TestSplitAndTrim(t *testing.T) { + testCases := []struct { + s string + sep string + cutset string + expected []string + }{ + {"a,b,c", ",", " ", []string{"a", "b", "c"}}, + {" a , b , c ", ",", " ", []string{"a", "b", "c"}}, + {" a, b, c ", ",", " ", []string{"a", "b", "c"}}, + {" , ", ",", " ", []string{"", ""}}, + {" ", ",", " ", []string{""}}, + } + + for _, tc := range testCases { + assert.Equal(t, tc.expected, SplitAndTrim(tc.s, tc.sep, tc.cutset), "%s", tc.s) + } +}