diff --git a/string.go b/string.go index 5022bea..4f91f77 100644 --- a/string.go +++ b/string.go @@ -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) { diff --git a/string_test.go b/string_test.go index 6c08d80..571008e 100644 --- a/string_test.go +++ b/string_test.go @@ -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")