What is unicode.IsSpace() Function in Golang

Golang unicode.IsSpace() function is “used to check if a given Unicode 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 and which are not.

That’s it!

Leave a Comment