Skip to content

Commit

Permalink
add KStr.StartsWith
Browse files Browse the repository at this point in the history
  • Loading branch information
kakuilan committed May 19, 2021
1 parent 02528c1 commit 8270eaf
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
22 changes: 22 additions & 0 deletions string.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,17 @@ func (ks *LkkString) StartsWith(str, sub string, ignoreCase bool) bool {
return false
}

// StartsWiths 字符串str是否以subs其中之一为开头.
func (ks *LkkString) StartsWiths(str string, subs []string, ignoreCase bool) (res bool) {
for _, sub := range subs {
res = ks.StartsWith(str, sub, ignoreCase)
if res {
break
}
}
return
}

// EndsWith 字符串str是否以sub结尾.
func (ks *LkkString) EndsWith(str, sub string, ignoreCase bool) bool {
if str != "" && sub != "" {
Expand All @@ -237,6 +248,17 @@ func (ks *LkkString) EndsWith(str, sub string, ignoreCase bool) bool {
return false
}

// EndsWiths 字符串str是否以subs其中之一为结尾.
func (ks *LkkString) EndsWiths(str string, subs []string, ignoreCase bool) (res bool) {
for _, sub := range subs {
res = ks.EndsWith(str, sub, ignoreCase)
if res {
break
}
}
return
}

// Trim 去除字符串首尾处的空白字符(或者其他字符).
// characterMask为要修剪的字符.
func (ks *LkkString) Trim(str string, characterMask ...string) string {
Expand Down
31 changes: 30 additions & 1 deletion string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3139,4 +3139,33 @@ func BenchmarkString_CountWords(b *testing.B) {
for i := 0; i < b.N; i++ {
_, _ = KStr.CountWords(helloOther)
}
}
}

func TestString_StartsWith(t *testing.T) {
var tests = []struct {
str string
sub string
ignoreCase bool
expected bool
}{
{"", "", false, false},
{helloEng, "", false, false},
{helloOther2, "hello", false, false},
{helloOther2, "Hello", false, true},
{helloOther2, "hello", true, true},
{helloOther2, "Hello 你好", false, true},
{helloOther2, "hello 你好", true, true},
{helloOther2, "world 世", true, false},
}
for _, test := range tests {
actual := KStr.StartsWith(test.str, test.sub, test.ignoreCase)
assert.Equal(t, actual, test.expected)
}
}

func BenchmarkString_StartsWith(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
KStr.StartsWith(helloOther2, "hello", true)
}
}

0 comments on commit 8270eaf

Please sign in to comment.