DEV Community

Cover image for How to check if the character is alphanumeric in GO
Saharat Paynok
Saharat Paynok

Posted on

How to check if the character is alphanumeric in GO

Understanding Characters in Go as Bytes

In Go, a string is equivalent to a slice of bytes.


Solution: Checking if a Character is Alphanumeric

To determine whether a character is alphanumeric (i.e., a letter or a digit), you can create a function that checks the byte value of the character.

Here’s an example implementation:

package main

func isAlphaNumeric(c byte) bool {
    // Check if the byte value falls within the range of alphanumeric characters
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
}

func main() {

    isAlphaNumeric('a') // true

    isAlphaNumeric('2') // true (digits are also considered alphanumeric)

    isAlphaNumeric('#') // false
}

Enter fullscreen mode Exit fullscreen mode

In the isAlphaNumeric function:
We check if the byte value c corresponds to a lowercase letter ('a' to 'z'), an uppercase letter ('A' to 'Z'), or a digit ('0' to '9').
If the condition is met, we return true; otherwise, we return false.


Let me know if you have an alternative solution or learned something from this post.

Top comments (0)