Skip to content

Commit

Permalink
✨ feat: strutil - add new func BeforeFirst, AfterFirst, AfterLast spl…
Browse files Browse the repository at this point in the history
…it funcs
  • Loading branch information
inhere committed Jul 24, 2023
1 parent 477d4d0 commit ecbbbc8
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
32 changes: 32 additions & 0 deletions strutil/split.go
Expand Up @@ -2,6 +2,38 @@ package strutil

import "strings"

// BeforeFirst get substring before first sep.
func BeforeFirst(s, sep string) string {
if i := strings.Index(s, sep); i >= 0 {
return s[:i]
}
return s
}

// AfterFirst get substring after first sep.
func AfterFirst(s, sep string) string {
if i := strings.Index(s, sep); i >= 0 {
return s[i+len(sep):]
}
return ""
}

// BeforeLast get substring before last sep.
func BeforeLast(s, sep string) string {
if i := strings.LastIndex(s, sep); i >= 0 {
return s[:i]
}
return s
}

// AfterLast get substring after last sep.
func AfterLast(s, sep string) string {
if i := strings.LastIndex(s, sep); i >= 0 {
return s[i+len(sep):]
}
return ""
}

/*************************************************************
* String split operation
*************************************************************/
Expand Down
22 changes: 22 additions & 0 deletions strutil/split_test.go
Expand Up @@ -8,6 +8,28 @@ import (
"github.com/gookit/goutil/testutil/assert"
)

func TestBeforeAfter(t *testing.T) {
// BeforeFirst
assert.Eq(t, "abc", strutil.BeforeFirst("abc", ":"))
assert.Eq(t, "abc", strutil.BeforeFirst("abc:123", ":"))
assert.Eq(t, "abc", strutil.BeforeFirst("abc:123:456", ":"))

// AfterFirst
assert.Eq(t, "", strutil.AfterFirst("abc", ":"))
assert.Eq(t, "123", strutil.AfterFirst("abc:123", ":"))
assert.Eq(t, "123:456", strutil.AfterFirst("abc:123:456", ":"))

// BeforeLast
assert.Eq(t, "abc", strutil.BeforeLast("abc", ":"))
assert.Eq(t, "abc", strutil.BeforeLast("abc:123", ":"))
assert.Eq(t, "abc:123", strutil.BeforeLast("abc:123:456", ":"))

// AfterLast
assert.Eq(t, "", strutil.AfterLast("abc", ":"))
assert.Eq(t, "123", strutil.AfterLast("abc:123", ":"))
assert.Eq(t, "456", strutil.AfterLast("abc:123:456", ":"))
}

func TestCut(t *testing.T) {
str := "hi,inhere"

Expand Down

0 comments on commit ecbbbc8

Please sign in to comment.