Skip to content

Instantly share code, notes, and snippets.

@luw2007
Created May 19, 2019 13:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save luw2007/1e345c9391b3d94d6efec5bc1c8a71c8 to your computer and use it in GitHub Desktop.
TrimSpace remove space, also in sentence. like: " a \t\r\n b " -> "a b"
package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
)
func isSpace(b byte) bool {
switch b {
case '\t', '\n', '\v', '\f', '\r', ' ':
return true
}
return false
}
// TrimSpace remove space, also in sentence.
// like:
// " a \t\r\n b " -> "a b"
func TrimSpace(b []byte) []byte {
var l, r int
r = len(b) - 1
// skip left space
for l < r && isSpace(b[l]) {
l++
}
// skip right space
for r >= 0 && isSpace(b[r]) {
r--
}
var i int
for l <= r {
if isSpace(b[l]) {
b[i] = ' '
// skip multi spaces
for l <= r && isSpace(b[l]) {
l++
}
} else {
b[i] = b[l]
l++
}
i++
}
return b[:i]
}
func main() {
datas := []struct {
in []byte
out []byte
}{
{nil, nil},
{[]byte(" "), []byte("")},
{[]byte("hi"), []byte("hi")},
{[]byte(" hi world "), []byte("hi world")},
{[]byte("\t hi\r\n world "), []byte("hi world")},
}
for _, data := range datas {
d := cmp.Diff(TrimSpace(data.in), data.out)
if d != "" {
fmt.Println(d)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment