From 2894bec80c62f80e3200a7c3140003eef84e64a4 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Wed, 31 May 2023 10:51:16 +0800 Subject: [PATCH] feat: add ContainsAll and ContainsAny --- strutil/string.go | 24 ++++++++++++++++++++++++ strutil/string_example_test.go | 31 +++++++++++++++++++++++++++++++ strutil/string_test.go | 16 ++++++++++++++++ 3 files changed, 71 insertions(+) diff --git a/strutil/string.go b/strutil/string.go index a7e8ea8..c38fe09 100644 --- a/strutil/string.go +++ b/strutil/string.go @@ -528,3 +528,27 @@ func HideString(origin string, start, end int, replaceChar string) string { return startStr + replaceStr + endStr } + +// ContainsAll return true if target string contains all the substrs. +// Play: todo +func ContainsAll(str string, substrs []string) bool { + for _, v := range substrs { + if !strings.Contains(str, v) { + return false + } + } + + return true +} + +// ContainsAny return true if target string contains any one of the substrs. +// Play: todo +func ContainsAny(str string, substrs []string) bool { + for _, v := range substrs { + if strings.Contains(str, v) { + return true + } + } + + return false +} diff --git a/strutil/string_example_test.go b/strutil/string_example_test.go index 43a21cb..b3c44cb 100644 --- a/strutil/string_example_test.go +++ b/strutil/string_example_test.go @@ -591,3 +591,34 @@ func ExampleHideString() { // 132****8976 // 1324265**** } + +func ExampleContainsAll() { + str := "hello world" + + result1 := ContainsAll(str, []string{"hello", "world"}) + result2 := ContainsAll(str, []string{"hello", "abc"}) + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // true + // false +} + +func ExampleContainsAny() { + str := "hello world" + + result1 := ContainsAny(str, []string{"hello", "world"}) + result2 := ContainsAny(str, []string{"hello", "abc"}) + result3 := ContainsAny(str, []string{"123", "abc"}) + + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + + // Output: + // true + // true + // false +} diff --git a/strutil/string_test.go b/strutil/string_test.go index f14635a..26c4994 100644 --- a/strutil/string_test.go +++ b/strutil/string_test.go @@ -450,3 +450,19 @@ func TestHideString(t *testing.T) { assert.Equal("1324265****", HideString(str, 7, 100, "*")) assert.Equal("13242658976", HideString(str, 100, 100, "*")) } + +func TestContainsAll(t *testing.T) { + assert := internal.NewAssert(t, "TestContainsAll") + + assert.Equal(true, ContainsAll("hello world", []string{"hello", "world"})) + assert.Equal(true, ContainsAll("hello world", []string{""})) + assert.Equal(false, ContainsAll("hello world", []string{"hello", "abc"})) +} + +func TestContainsAny(t *testing.T) { + assert := internal.NewAssert(t, "TestContainsAny") + + assert.Equal(true, ContainsAny("hello world", []string{"hello", "world"})) + assert.Equal(true, ContainsAny("hello world", []string{"hello", "abc"})) + assert.Equal(false, ContainsAny("hello world", []string{"123", "abc"})) +}