diff options
| author | Shulhan <m.shulhan@gmail.com> | 2020-01-07 12:02:31 +0700 |
|---|---|---|
| committer | Shulhan <m.shulhan@gmail.com> | 2020-01-07 12:02:31 +0700 |
| commit | 84ba21902eef9620dc129a03f7ceec7d4ba0fc19 (patch) | |
| tree | c107eb86851e27bc3a1b230b45e5ad625d251e08 /lib/strings | |
| parent | 887038fe4b0373534256e95dd3acf240f6977cd8 (diff) | |
| download | pakakeh.go-84ba21902eef9620dc129a03f7ceec7d4ba0fc19.tar.xz | |
strings: add function to reverse a string
Diffstat (limited to 'lib/strings')
| -rw-r--r-- | lib/strings/string.go | 15 | ||||
| -rw-r--r-- | lib/strings/string_test.go | 16 |
2 files changed, 31 insertions, 0 deletions
diff --git a/lib/strings/string.go b/lib/strings/string.go index 491edd7f..69e63893 100644 --- a/lib/strings/string.go +++ b/lib/strings/string.go @@ -164,6 +164,21 @@ func MergeSpaces(text string, withline bool) string { } // +// Reverse the string. +// +func Reverse(input string) string { + r := []rune(input) + x := 0 + y := len(r) - 1 + for x < len(r)/2 { + r[x], r[y] = r[y], r[x] + x += 1 + y -= 1 + } + return string(r) +} + +// // 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 0afdcdf5..11644de8 100644 --- a/lib/strings/string_test.go +++ b/lib/strings/string_test.go @@ -169,6 +169,22 @@ func TestMergeSpaces(t *testing.T) { } } +func TestReverse(t *testing.T) { + cases := []struct { + input string + exp string + }{{ + input: "The quick bròwn 狐 jumped over the lazy 犬", + exp: "犬 yzal eht revo depmuj 狐 nwòrb kciuq ehT", + }} + + for _, c := range cases { + got := Reverse(c.input) + + test.Assert(t, "Reverse", c.exp, got, true) + } +} + func TestSplit(t *testing.T) { cases := []struct { text string |
