Created
May 19, 2019 13:17
Star
You must be signed in to star a gist
TrimSpace remove space, also in sentence. like: " a \t\r\n b " -> "a b"
This file contains 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 | |
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