shad-go/utf8/spacecollapse/collapse.go

46 lines
925 B
Go
Raw Normal View History

2022-02-10 22:06:57 +00:00
//go:build !solution
2020-02-24 19:54:48 +00:00
package spacecollapse
2020-02-24 19:54:48 +00:00
import (
"strings"
"unicode"
)
// 1 alloc/op, best ns/op but more iterations overall
2020-02-24 19:54:48 +00:00
func CollapseSpaces(input string) string {
output := strings.Builder{}
output.Grow(len(input))
writeSpace := true
for _, r := range input {
if unicode.IsSpace(r) {
if writeSpace {
output.WriteRune(' ')
}
writeSpace = false
} else {
output.WriteRune(r)
writeSpace = true
}
}
return output.String()
2020-02-24 19:54:48 +00:00
}
// 3 allocs/op for runes slice, output slice and output string
// func CollapseSpaces(input string) string {
// runes := []rune(input)
// output, writeSpace := make([]rune, 0, len(runes)), true
// for _, r := range input {
// if unicode.IsSpace(r) {
// if writeSpace {
// output = append(output, ' ')
// }
// writeSpace = false
// } else {
// output = append(output, r)
// writeSpace = true
// }
// }
// return string(output)
// }