From ee042feb6811a2dfb7abc6e3ff5fdf4d1a53c9c3 Mon Sep 17 00:00:00 2001 From: ShyunnY <1147212064@qq.com> Date: Sat, 26 Aug 2023 21:25:28 +0800 Subject: [PATCH] feat: add strings reverse and strings contain func in utils.strings file --- utils/strings.go | 23 +++++++++++++++++++++++ utils/strings_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/utils/strings.go b/utils/strings.go index 109d132f1e..a8d833f2f8 100644 --- a/utils/strings.go +++ b/utils/strings.go @@ -73,3 +73,26 @@ func EqualFold(b, s string) bool { } return true } + +// Reverse reverse target string +func Reverse(s string) string { + rs := []rune(s) + + for head, tail := 0, len(rs)-1; head < tail; head, tail = head+1, tail-1 { + rs[head], rs[tail] = rs[tail], rs[head] + } + + return string(rs) +} + +// Contain checks if the target string is contained in the strs +func Contain(strs []string, s string) bool { + + for _, str := range strs { + if str == s { + return true + } + } + + return false +} diff --git a/utils/strings_test.go b/utils/strings_test.go index c0de5875c6..776748e6f9 100644 --- a/utils/strings_test.go +++ b/utils/strings_test.go @@ -215,3 +215,35 @@ func Test_EqualFold(t *testing.T) { res = EqualFold("/MY4/NAME/IS/:PARAM/*", "/my4/nAME/IS/:param/*") AssertEqual(t, true, res) } + +func Test_Reverse(t *testing.T) { + t.Parallel() + + res := Reverse("abcde") + AssertEqual(t, "edcba", res) + + res = Reverse("abcd") + AssertEqual(t, "dcba", res) + + res = Reverse("a") + AssertEqual(t, "a", res) + + res = Reverse("") + AssertEqual(t, "", res) +} + +func Test_Contain(t *testing.T) { + t.Parallel() + + res := Contain([]string{"a", "b", "c", "d"}, "b") + AssertEqual(t, true, res) + + res = Contain([]string{"a,b,c,d"}, "e") + AssertEqual(t, false, res) + + res = Contain([]string{}, "a") + AssertEqual(t, false, res) + + res = Contain([]string{"a"}, "") + AssertEqual(t, false, res) +}