How to Use strconv.IsGraphic() Function in Golang

Golang strconv.isGraphic() function is used to check whether the rune is defined as a Graphic by Unicode”. Such characters include letters, marks, numbers, punctuation, symbols, and spaces, from categories L, M, N, P, S, and Zs.

“Graphic” means any Unicode rune that is not a control character, not a formatting character, not a surrogate, not an unassigned code point, and not a non-character.

Syntax

func IsGraphic(r rune) bool

Parameters

rune: It takes one parameter of rune type.

Return value

It returns true if the rune is defined as a Graphic by Unicode. Otherwise, return false.

Example 1: How to Use strconv.IsGraphic() Function

package main

import (
  "fmt"
  "strconv"
)

func main() {
  fmt.Println(strconv.IsGraphic('πŸ˜€'))
  fmt.Println(strconv.IsGraphic('πŸ€–'))
}

Output

true
true

Example 2: Complex usage of strconv.IsGraphic() function

package main

import (
  "fmt"
  "strconv"
)

func main() {
  // Define a string containing various characters
  str := "Hello, δΈ–η•Œ! 🌍"

  // Convert the string to a slice of runes for individual inspection
  runes := []rune(str)

  // Create a map to store the result for each rune
  results := make(map[rune]bool)

  // Loop over the slice of runes, check each one with strconv.IsGraphic
  for _, r := range runes {
    results[r] = strconv.IsGraphic(r)
  }

  // Print results
  for r, isGraphic := range results {
    fmt.Printf("Rune %q is graphic: %t\n", r, isGraphic)
  }

  // Check if all characters in the string are graphic
  allGraphic := true
  for _, isGraphic := range results {
    allGraphic = allGraphic && isGraphic
  }

  fmt.Printf("All characters in string %q are graphic: %t\n", str, allGraphic)
}

Output

Rune 'o' is graphic: true
Rune ',' is graphic: true
Rune ' ' is graphic: true
Rune 'δΈ–' is graphic: true
Rune '!' is graphic: true
Rune '🌍' is graphic: true
Rune 'e' is graphic: true
Rune 'l' is graphic: true
Rune 'η•Œ' is graphic: true
Rune 'H' is graphic: true
All characters in string "Hello, δΈ–η•Œ! 🌍" are graphic: true

That’s it.

Leave a Comment