Unicode.IsSpace
Whitespace characters often need to be handled in a different way than other characters. We need to test for spaces (and other whitespace chars).
With the unicode package, we can test for all whitespace without recalling the entire set ourselves. The unicode.IsSpace
func
is useful in many programs.
Here we loop over the runes in a string
. We use unicode.IsSpace
on each rune
to see if it is a space character. We also detect the ASCII code 32 (for space).
unicode.IsSpace
func
.package main import ( "fmt" "unicode" ) func main() { value := "\tHello, friends\n" // Loop over chars in string. for _, v := range value { // Test each character to see if it is whitespace. if unicode.IsSpace(v) { fmt.Println("Is space:", v) if v == 32 { fmt.Println("ASCII code for space") } } } }Is space: 9 Is space: 32 ASCII code for space Is space: 10
TrimFunc
, IsSpace
Consider a func
like TrimFunc
. The second argument required with TrimFunc
is a func
. We can pass unicode.IsSpace
directly as the second argument.
IsSpace
method ourselves.package main import ( "fmt" "unicode" "strings" ) func main() { value := "\n Hello, friends" // Use unicode.IsSpace as the func argument to TrimFunc. result := strings.TrimFunc(value, unicode.IsSpace) // Print before and after. fmt.Println("[" + value + "]") fmt.Println("[" + result + "]") }[ Hello, friends] [Hello, friends]
The unicode module in Go has many methods that can be used to test ranges of characters. These funcs can lead to simpler, clearer and more standard Go code.