How to Check If String is Whitespace in Golang

You can check if a string is whitespace in Golang by using the “unicode.IsSpace()” function.

Example 1

package main

import (
  "fmt"
  "unicode"
)

func main() {
  str := " " // a string containing only whitespace

  // loop through each character in the string
  for _, c := range str {
  // check if the character is a whitespace character
    if !unicode.IsSpace(c) {
      fmt.Println("String is not whitespace")
      return
    }
  }

  fmt.Println("String is whitespace")
}

Output

String is whitespace

In this code example, the unicode.IsSpace() function checks if each character in the string is a whitespace character. Since we provided a string with only whitespace runes, it returns the “String is whitespace” output.

The program will output “String is whitespace” if the string contains only whitespace characters. Otherwise, it will output “String is not whitespace”.

Example 2

Let’s pass the non-whitespace string and see what the output is.

package main

import (
  "fmt"
  "unicode"
)

func main() {
  str := "KRU" // a string containing non-whitespace runes

  // loop through each character in the string
  for _, c := range str {
  // check if the character is a whitespace rune
    if !unicode.IsSpace(c) {
      fmt.Println("String is not whitespace")
      return
    }
  }
  fmt.Println("String is whitespace")
}

Output

String is not whitespace

That’s it!