Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add SubstrCount and test case. #75

Merged
merged 1 commit into from Dec 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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