Check if a character is alphanumeric in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

Depending on your use case, you may need to check if a character is alphanumeric or not in Arduino. One example can be validating password strings, wherein you’ve allowed only alphanumeric characters for passwords. Or checking file names for storage in SD Card (sometimes some special characters are not allowed in file names). Arduino has an inbuilt function which checks whether a given character is alphanumeric or not. As you would have guessed, the function is isAlphaNumeric() and it takes in a character as the argument, and returns a Boolean.

Example

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   char c1 = 'a';
   char c2 = '1';
   char c3 = '%';

   if (isAlphaNumeric(c1)) {
      Serial.println("c1 is AlphaNumeric!");
   } else {
      Serial.println("c1 is NOT AlphaNumeric!");
   }

   if (isAlphaNumeric(c2)) {
      Serial.println("c2 is AlphaNumeric!");
   } else {
      Serial.println("c2 is NOT AlphaNumeric!");
   }

   if (isAlphaNumeric(c3)) {
      Serial.println("c3 is AlphaNumeric!");
   } else {
      Serial.println("c3 is NOT AlphaNumeric!");
   }
}

void loop() {
   // put your main code here, to run repeatedly:
}

Output

The Serial Monitor output is shown below −

As you can see, the function works as expected, and returns true for alphabets and numbers, but not for special characters. You can try this out for other characters.

raja
Published on 31-May-2021 14:08:57
Advertisements