Skip to content

Commit

Permalink
✨ up: strutil - add new function: SplitByWhitespace
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Nov 7, 2024
1 parent aef1d43 commit 342cd12
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
13 changes: 12 additions & 1 deletion strutil/split.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package strutil

import "strings"
import (
"regexp"
"strings"
)

// BeforeFirst get substring before first sep.
func BeforeFirst(s, sep string) string {
Expand Down Expand Up @@ -137,6 +140,14 @@ func SplitNTrimmed(s, sep string, n int) (ss []string) {
return
}

// 根据空白字符(空格,TAB,换行等)分隔字符串
var whitespaceRegexp = regexp.MustCompile("\\s+")

// SplitByWhitespace Separate strings by whitespace characters (space, TAB, newline, etc.)
func SplitByWhitespace(s string) []string {
return whitespaceRegexp.Split(s, -1)
}

// Substr for a string.
// if length <= 0, return pos to end.
func Substr(s string, pos, length int) string {
Expand Down
8 changes: 8 additions & 0 deletions strutil/split_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,14 @@ func TestSplitTrimmed(t *testing.T) {
assert.Eq(t, `[]string{"a", ", b,c"}`, fmt.Sprintf("%#v", ss))
}

func TestSplitByWhitespace(t *testing.T) {
ss := strutil.SplitByWhitespace("a b c")
assert.Eq(t, `[]string{"a", "b", "c"}`, fmt.Sprintf("%#v", ss))

ss = strutil.SplitByWhitespace("a\r\nb\tc d")
assert.Eq(t, `[]string{"a", "b", "c", "d"}`, fmt.Sprintf("%#v", ss))
}

func TestSubstr(t *testing.T) {
assert.Eq(t, "abc", strutil.Substr("abcDef", 0, 3))
assert.Eq(t, "cD", strutil.Substr("abcDef", 2, 2))
Expand Down

0 comments on commit 342cd12

Please sign in to comment.