What is unicode.IsSpace() Function in Golang

The unicode.IsSpace() is a built-in Golang function that checks if a given Unicode code point is a whitespace character. The isSpace() function takes a single argument of type rune, an alias for the int32 type, represents a Unicode code point, and returns a boolean value that suggests if the given code point is a whitespace character.

Syntax

func IsSpace(r rune) bool

Parameters

The IsSpace() function takes a “rune” as an argument. Rune is a superset of ASCII or an alias of int32. It contains all the characters available in the world’s writing system, including accents and other diacritical marks, control codes like tab and carriage return, and assigns each one a standard number.

Return value

The IsSpace() function checks if the rune is a space character as defined by Unicode’s White Space property; in the Latin-1 space this is: ‘\t’, ‘\n’, ‘\v’, ‘\f’, ‘\r’, ‘ ‘, U+0085 (NEL), U+00A0 (NBSP).

Example

In this code, we will pass a string with white and non-whitespace characters and get the output in which 

package main

import (
  "fmt"
  "unicode"
)

func main() {
  str := " \t\n e n "

  // Loop over each character in the string and check if it's a whitespace character
  for _, r := range str {
    if unicode.IsSpace(r) {
      fmt.Printf("'%c' is a whitespace character\n", r)
    } else {
      fmt.Printf("'%c' is not a whitespace character\n", r)
    }
  }
}

Output

' ' is a whitespace character
' ' is a whitespace character
' ' is a whitespace character
'
' is a whitespace character
' ' is a whitespace character
'e' is not a whitespace character
' ' is a whitespace character
'n' is not a whitespace character
' ' is a whitespace character
' ' is a whitespace character

In this example, the unicode.IsSpace() function checks if each character in the string str is a whitespace character.

The program’s output will suggest which characters are whitespace characters and which are not.

Conclusion

Whitespace characters often need to be handled differently than other characters.

Use the unicode.IsSpace() function to check if a unicode character is a white space character.

With the unicode package, we can check for all whitespace without identifying the entire set.

Leave a Comment