What is the fastest way to strip all whitespace from some arbitrary string in Go.
I am chaining two function from the string package:
response = stri
From rosettacode.org :
You can find this kind of function :
func stripChars(str, chr string) string {
return strings.Map(func(r rune) rune {
if strings.IndexRune(chr, r) < 0 {
return r
}
return -1
}, str)
}
So, simply replacing chr
by " "
here should be enough to do the trick and remove the whitespaces.
Beware that there are other kind of whitespaces defined by unicode (like line break, nbsp, ...), and you might also want to get rid of those (especially if you're working with external data you don't really have control over)
This would be done that way:
func stripSpaces(str string) string {
return strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
// if the character is a space, drop it
return -1
}
// else keep it in the string
return r
}, str)
}
Then simply apply to your string. Hope it works, didn't test.