Skip to content

Commit

Permalink
🎨 Add string util SubStringBetween
Browse files Browse the repository at this point in the history
  • Loading branch information
88250 committed Mar 24, 2024
1 parent 5293bc5 commit 3c1bb82
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
26 changes: 26 additions & 0 deletions string.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,32 @@ import (
"unsafe"
)

// SubStringBetween gets the first substring between the start and end.
func (gs *GuluStr) SubStringBetween(s, start, end string) string {
startIndex := strings.Index(s, start)
if -1 == startIndex {
return ""
}
endIndex := strings.Index(s, end)
if -1 == endIndex {
return ""
}
return s[startIndex+len(start) : endIndex]
}

// LastSubStringBetween gets the last substring between the start and end.
func (gs *GuluStr) LastSubStringBetween(s, start, end string) string {
startIndex := strings.LastIndex(s, start)
if -1 == startIndex {
return ""
}
endIndex := strings.LastIndex(s, end)
if -1 == endIndex {
return ""
}
return s[startIndex+len(start) : endIndex]
}

// Equal determines whether the slice1 is equal to the slice2.
func (gs *GuluStr) Equal(slice1 []string, slice2 []string) bool {
if len(slice1) != len(slice2) {
Expand Down
18 changes: 18 additions & 0 deletions string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,24 @@ import (
"testing"
)

func TestSubStringBetween(t *testing.T) {
expected := "bar"
got := Str.SubStringBetween("foobarbaz", "foo", "baz")
if expected != got {
t.Errorf("expected [%s], got [%s]", expected, got)
return
}
}

func TestLastSubStringBetween(t *testing.T) {
expected := "bar"
got := Str.LastSubStringBetween("foobarbaz", "foo", "baz")
if expected != got {
t.Errorf("expected [%s], got [%s]", expected, got)
return
}
}

func TestEqual(t *testing.T) {
if !Str.Equal([]string{"foo", "bar"}, []string{"foo", "bar"}) {
t.Error("[\"foo\", \"bar\"] and [\"foo\", \"bar\"] should be equal")
Expand Down

0 comments on commit 3c1bb82

Please sign in to comment.