From b57a8abd59fb6eb85c075771be921c7a2379035c Mon Sep 17 00:00:00 2001 From: Huan Du Date: Thu, 8 Jan 2015 20:58:13 +0800 Subject: [PATCH] refs #7. reverse string. --- manipulate.go | 26 ++++++++++++++++++++++++++ manipulate_test.go | 16 ++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 manipulate.go create mode 100644 manipulate_test.go diff --git a/manipulate.go b/manipulate.go new file mode 100644 index 0000000..86bfcae --- /dev/null +++ b/manipulate.go @@ -0,0 +1,26 @@ +// Copyright 2015 Huan Du. All rights reserved. +// Licensed under the MIT license that can be found in the LICENSE file. + +package xstrings + +import ( + "unicode/utf8" +) + +// Reverse a utf8 encoded string. +func Reverse(str string) string { + var size int + + tail := len(str) + buf := make([]byte, tail) + s := buf + + for len(str) > 0 { + _, size = utf8.DecodeRuneInString(str) + tail -= size + s = append(s[:tail], []byte(str[:size])...) + str = str[size:] + } + + return string(buf) +} diff --git a/manipulate_test.go b/manipulate_test.go new file mode 100644 index 0000000..6f109db --- /dev/null +++ b/manipulate_test.go @@ -0,0 +1,16 @@ +// Copyright 2015 Huan Du. All rights reserved. +// Licensed under the MIT license that can be found in the LICENSE file. + +package xstrings + +import ( + "testing" +) + +func TestReverse(t *testing.T) { + runTestCases(t, Reverse, map[string]string{ + "reverse string": "gnirts esrever", + "中文如何?": "?何如文中", + "中en文混~排怎样?a": "a?样怎排~混文ne中", + }) +}