Home
Go
unicode.IsSpace (If Char Is Whitespace)
Updated Jun 28, 2023
Dot Net Perls
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 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.
func
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen