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) + } + } +}