Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// string/string.go package strutil import "strings" // Reverse returns the Unicode-correct reversal of s. func Reverse(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } // IsPalindrome reports whether s reads the same forwards and backwards. func IsPalindrome(s string) bool { s = strings.ToLower(s) return s == Reverse(s) } // string/string_test.go package strutil_test import ( "testing" "github.com/example/app/strutil" ) // Example — doubles as documentation and a runnable test. func ExampleReverse() { fmt.Println(strutil.Reverse("Hello, 世界")) // Output: 界世 ,olleH } // Benchmark — run with: go test -bench=BenchmarkReverse -benchmem func BenchmarkReverse(b *testing.B) { s := "The quick brown fox jumps over the lazy dog" b.ResetTimer() for i := 0; i < b.N; i++ { strutil.Reverse(s) } } func TestIsPalindrome(t *testing.T) { cases := []struct { in string want bool }{ {"racecar", true}, {"hello", false}, {"A", true}, {"", true}, } for _, c := range cases { if got := strutil.IsPalindrome(c.in); got != c.want { t.Errorf("IsPalindrome(%q) = %v, want %v", c.in, got, c.want) } } }
Result
Open