From 2d07e6c6eeda93b6a2b81ee1e9253068e3ac5a6b Mon Sep 17 00:00:00 2001 From: dennis Date: Mon, 30 Oct 2023 11:38:38 +0800 Subject: [PATCH] Add: StringUtils.Substring --- StringUtils.go | 33 +++++++++++++++++++++++++++++ StringUtils_test.go | 51 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 StringUtils_test.go diff --git a/StringUtils.go b/StringUtils.go index 07bde77..1fc82f7 100644 --- a/StringUtils.go +++ b/StringUtils.go @@ -33,3 +33,36 @@ func (s *StringUtils) LeftPad(str string, size int, padStr string) string { return strings.Repeat(padStr, padCount) + str } + +func (s *StringUtils) Substring(str string, start, end int) string { + if str == "" { + return str + } + + runes := []rune(str) + + if end < 0 { + end = len(runes) + end + } + if start < 0 { + start = len(runes) + start + } + + if end > len(str) { + end = len(str) + } + + if start > end { + return EMPTY + } + + if start < 0 { + start = 0 + } + + if end < 0 { + end = 0 + } + + return string(runes[start:end]) +} diff --git a/StringUtils_test.go b/StringUtils_test.go new file mode 100644 index 0000000..4ede209 --- /dev/null +++ b/StringUtils_test.go @@ -0,0 +1,51 @@ +package golanghelper_test + +import ( + "testing" + + "gitlab-ce.niaulang.com/niau-lang/golanghelper" +) + +func TestSubstring(t *testing.T) { + stringUtils := golanghelper.StringUtils{} + + s := stringUtils.Substring("", 0, 0) + if s != "" { + t.Errorf("預期的值為空字串, 卻回傳 %v", s) + } + + s = stringUtils.Substring("abc", 0, 2) + if s != "ab" { + t.Errorf("預期的值為 ab, 卻回傳 %v", s) + } + + s = stringUtils.Substring("abc", 2, 0) + if s != "" { + t.Errorf("預期的值為空字串, 卻回傳 %v", s) + } + + s = stringUtils.Substring("abc", 2, 4) + if s != "c" { + t.Errorf("預期的值為 c, 卻回傳 %v", s) + } + + s = stringUtils.Substring("abc", 4, 6) + if s != "" { + t.Errorf("預期的值為空字串, 卻回傳 %v", s) + } + + s = stringUtils.Substring("abc", 2, 2) + if s != "" { + t.Errorf("預期的值為 ab, 卻回傳 %v", s) + } + + s = stringUtils.Substring("abc", -2, -1) + if s != "b" { + t.Errorf("預期的值為 b, 卻回傳 %v", s) + } + + s = stringUtils.Substring("abc", -4, 2) + if s != "ab" { + t.Errorf("預期的值為 ab, 卻回傳 %v", s) + } +}