From d401d5279087c0d6125507288523e9653ef99d11 Mon Sep 17 00:00:00 2001 From: Jay Zhang Date: Mon, 7 Oct 2019 18:07:07 +0800 Subject: [PATCH] feat: reverse echo --- .gitignore | 1 + cmd/echor/main.go | 16 ++++++++++++++++ stringutil/reverse.go | 11 +++++++++++ stringutil/reverse_test.go | 20 ++++++++++++++++++++ 4 files changed, 48 insertions(+) create mode 100644 cmd/echor/main.go create mode 100644 stringutil/reverse.go create mode 100644 stringutil/reverse_test.go diff --git a/.gitignore b/.gitignore index 5bd4d61..dfd1914 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ *.dylib cmd/diagnosis/diagnosis cmd/diagnosis/diagnosis.* +cmd/echor/echor # Test binary, build with `go test -c` *.test diff --git a/cmd/echor/main.go b/cmd/echor/main.go new file mode 100644 index 0000000..af79241 --- /dev/null +++ b/cmd/echor/main.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" + "os" + + "github.com/wangyoucao577/go-project-layout/stringutil" +) + +func main() { + if len(os.Args) > 1 { + fmt.Println(stringutil.Reverse(os.Args[1])) + } else { + fmt.Println() // print empty string + } +} diff --git a/stringutil/reverse.go b/stringutil/reverse.go new file mode 100644 index 0000000..40942f8 --- /dev/null +++ b/stringutil/reverse.go @@ -0,0 +1,11 @@ +// Package stringutil contains utility functions for working with strings. +package stringutil + +// Reverse returns its argument string reversed rune-wise left to right. +func Reverse(s string) string { + r := []rune(s) + for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { + r[i], r[j] = r[j], r[i] + } + return string(r) +} diff --git a/stringutil/reverse_test.go b/stringutil/reverse_test.go new file mode 100644 index 0000000..50774b7 --- /dev/null +++ b/stringutil/reverse_test.go @@ -0,0 +1,20 @@ +package stringutil + +import "testing" + +func TestReverse(t *testing.T) { + cases := []struct { + in, want string + }{ + {"Hello, world", "dlrow ,olleH"}, + {"Hello, 世界", "界世 ,olleH"}, + {"", ""}, + } + + for _, c := range cases { + got := Reverse(c.in) + if got != c.want { + t.Errorf("Reverse(%q) == %q, want %q", c.in, got, c.want) + } + } +}