Skip to content

Commit

Permalink
mstr: add Split function
Browse files Browse the repository at this point in the history
This is a convenience for strings.Split, with the addition that an empty input
string yields an empty output slice rather than a slice of one empty field.
  • Loading branch information
creachadair committed Nov 22, 2024
1 parent d370259 commit 174723f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
11 changes: 10 additions & 1 deletion mstr/mstr.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,23 @@ func Trunc(s string, n int) string {

// Lines splits its argument on newlines. It is a convenience function for
// [strings.Split], except that it returns empty if s == "" and treats a
// trailing newline as the end of the file.
// trailing newline as the end of the file rather than an empty line.
func Lines(s string) []string {
if s == "" {
return nil
}
return strings.Split(strings.TrimSuffix(s, "\n"), "\n")
}

// Split splits its argument on sep. It is a convenience function for
// [strings.Split], except that it returns empty if s == "".
func Split(s, sep string) []string {
if s == "" {
return nil
}
return strings.Split(s, sep)
}

// CompareNatural compares its arguments lexicographically, but treats runs of
// decimal digits as the spellings of natural numbers and compares their values
// instead of the individual digits.
Expand Down
23 changes: 22 additions & 1 deletion mstr/mstr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
gocmp "github.com/google/go-cmp/cmp"
)

func TestString(t *testing.T) {
func TestTrunc(t *testing.T) {
tests := []struct {
input string
size int
Expand Down Expand Up @@ -59,6 +59,27 @@ func TestLines(t *testing.T) {
}
}

func TestSplit(t *testing.T) {
tests := []struct {
input, sep string
want []string
}{
{"", "x", nil},
{"y", "x", []string{"y"}},
{"x", "x", []string{"", ""}},
{"ax", "x", []string{"a", ""}},
{"xa", "x", []string{"", "a"}},
{"axbxc", "x", []string{"a", "b", "c"}},
{"axxc", "x", []string{"a", "", "c"}},
{"a,b,c,,d", ",", []string{"a", "b", "c", "", "d"}},
}
for _, tc := range tests {
if diff := gocmp.Diff(mstr.Split(tc.input, tc.sep), tc.want); diff != "" {
t.Errorf("Split %q on %q (-got, +want):\n%s", tc.input, tc.sep, diff)
}
}
}

func TestCompareNatural(t *testing.T) {
tests := []struct {
a, b string
Expand Down

0 comments on commit 174723f

Please sign in to comment.