Created
February 12, 2020 12:59
-
-
Save rodrigodev/934a762ee5f4dca3a91909efd5697239 to your computer and use it in GitHub Desktop.
Removes all whites spaces, examples and benchmarks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main_test | |
| import ( | |
| "strings" | |
| "unicode" | |
| "testing" | |
| ) | |
| func SpaceMap(str string) string { | |
| return strings.Map(func(r rune) rune { | |
| if unicode.IsSpace(r) { | |
| return -1 | |
| } | |
| return r | |
| }, str) | |
| } | |
| func SpaceFieldsJoin(str string) string { | |
| return strings.Join(strings.Fields(str), "") | |
| } | |
| func SpaceStringsBuilder(str string) string { | |
| var b strings.Builder | |
| b.Grow(len(str)) | |
| for _, ch := range str { | |
| if !unicode.IsSpace(ch) { | |
| b.WriteRune(ch) | |
| } | |
| } | |
| return b.String() | |
| } | |
| func BenchmarkSpaceMap(b *testing.B) { | |
| for n := 0; n < b.N; n++ { | |
| SpaceMap(data) | |
| } | |
| } | |
| func BenchmarkSpaceFieldsJoin(b *testing.B) { | |
| for n := 0; n < b.N; n++ { | |
| SpaceFieldsJoin(data) | |
| } | |
| } | |
| func BenchmarkSpaceStringsBuilder(b *testing.B) { | |
| for n := 0; n < b.N; n++ { | |
| SpaceStringsBuilder(data) | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/questions/32081808/strip-all-whitespace-from-a-string