unicode.IsSpace (If Char Is Whitespace)Use the unicode.IsSpace func from the unicode package to test for space chars. Call TrimFunc.
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.
First example. 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).
Result The tab, newline and space characters are detected by the 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.
Tip This style of code is cleaner and less prone to bugs than implementing a custom 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]
A review. The unicode module in Golang has many methods that can be used to test ranges of characters. These funcs can lead to simpler, clearer and more standard Golang code.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2023 Sam Allen.