Skip to content

Commit

Permalink
Merge pull request #75 from huangkuan123/SubstrCount
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Dec 12, 2022
2 parents ea10bc7 + 1bff3b3 commit 31b8753
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -1097,6 +1097,7 @@ func PrettyJSON(v any) (string, error)
func RenderTemplate(input string, data any, fns template.FuncMap, isFile ...bool) string
func RenderText(input string, data any, fns template.FuncMap, isFile ...bool) string
func WrapTag(s, tag string) string
func SubstrCount(s string, needle string, params ...uint64) (int, error)
```
### System Utils
Expand Down
33 changes: 33 additions & 0 deletions strutil/strutil.go
Expand Up @@ -4,6 +4,7 @@ package strutil
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strings"
"text/template"
Expand Down Expand Up @@ -88,3 +89,35 @@ func WrapTag(s, tag string) string {
}
return fmt.Sprintf("<%s>%s</%s>", tag, s, tag)
}

// SubstrCount returns the number of times the substr substring occurs in the s string.
// Actually, it comes from strings.Count().
// s The string to search in
// substr The substring to search for
// params[0] The offset where to start counting.
// params[1] The maximum length after the specified offset to search for the substring.
func SubstrCount(s string, substr string, params ...uint64) (int, error) {
larg := len(params)
hasArgs := larg != 0
if hasArgs && larg > 2 {
return 0, errors.New("too many parameters")
}
if !hasArgs {
return strings.Count(s, substr), nil
}
strlen := len(s)
offset := 0
end := strlen
if hasArgs {
offset = int(params[0])
if larg == 2 {
length := int(params[1])
end = offset + length
}
if end > strlen {
end = strlen
}
}
s = string([]rune(s)[offset:end])
return strings.Count(s, substr), nil
}
17 changes: 17 additions & 0 deletions strutil/strutil_test.go
Expand Up @@ -34,6 +34,23 @@ func TestWrapTag(t *testing.T) {
assert.Eq(t, "<info>abc</info>", strutil.WrapTag("abc", "info"))
}

func TestSubstrCount(t *testing.T) {
s := "I'm fine, thank you, and you"
substr := "you"
res, err := strutil.SubstrCount(s, substr)
assert.NoErr(t, err)
assert.Eq(t, 2, res)
res1, err := strutil.SubstrCount(s, substr, 18)
assert.NoErr(t, err)
assert.Eq(t, 1, res1)
res2, err := strutil.SubstrCount(s, substr, 17, 100)
assert.NoErr(t, err)
assert.Eq(t, 1, res2)
res3, err := strutil.SubstrCount(s, substr, 16)
assert.NoErr(t, err)
assert.Eq(t, 2, res3)
}

func TestPrettyJSON(t *testing.T) {
tests := []any{
map[string]int{"a": 1},
Expand Down

0 comments on commit 31b8753

Please sign in to comment.