diff options
| author | Shulhan <m.shulhan@gmail.com> | 2020-03-29 04:15:44 +0700 |
|---|---|---|
| committer | Shulhan <m.shulhan@gmail.com> | 2020-03-29 04:15:44 +0700 |
| commit | f4912dbb53e00f3aeb34cf26ca6b5d9588ba3533 (patch) | |
| tree | 87fbb3554d0005975563e53fcbabed2b0cc9ad90 /lib/strings | |
| parent | b886d935c48d82bc445e645921264128d63b2dad (diff) | |
| download | pakakeh.go-f4912dbb53e00f3aeb34cf26ca6b5d9588ba3533.tar.xz | |
strings: add function SingleSpace
The SingleSpace function convert all sequences of white spaces into
single space ' '.
Diffstat (limited to 'lib/strings')
| -rw-r--r-- | lib/strings/string.go | 26 | ||||
| -rw-r--r-- | lib/strings/string_test.go | 16 |
2 files changed, 42 insertions, 0 deletions
diff --git a/lib/strings/string.go b/lib/strings/string.go index 5eb7d6b7..68aedb9d 100644 --- a/lib/strings/string.go +++ b/lib/strings/string.go @@ -138,6 +138,32 @@ func Reverse(input string) string { } // +// SingleSpace convert all sequences of white spaces into single space ' '. +// +func SingleSpace(in string) string { + var isspace bool + out := make([]rune, 0, len(in)) + for _, r := range in { + if unicode.IsSpace(r) { + if isspace { + continue + } + isspace = true + continue + } + if isspace { + out = append(out, ' ') + isspace = false + } + out = append(out, r) + } + if isspace { + out = append(out, ' ') + } + return string(out) +} + +// // Split given a text, return all words in text. // // A word is any sequence of character which have length equal or greater than diff --git a/lib/strings/string_test.go b/lib/strings/string_test.go index 7ee0c078..d161dfd7 100644 --- a/lib/strings/string_test.go +++ b/lib/strings/string_test.go @@ -117,6 +117,22 @@ func TestReverse(t *testing.T) { } } +func TestSingleSpace(t *testing.T) { + cases := []struct { + in string + exp string + }{{ + in: "", + }, { + in: " \t\v\r\n\r\n\fa \t\v\r\n\r\n\f", + exp: " a ", + }} + for _, c := range cases { + got := SingleSpace(c.in) + test.Assert(t, c.in, c.exp, got, true) + } +} + func TestSplit(t *testing.T) { cases := []struct { text string |
