Skip to content

← Back to Overview

Check if Character is Alphanumeric

Concept Explanation

What is it?

This program determines whether a given single character is alphanumeric. An alphanumeric character is any character that is either an alphabet (A-Z, a-z) or a digit (0-9). It distinguishes alphanumeric characters from symbols, punctuation, and whitespace.

Why is it important?

Character classification into categories like "alphanumeric" is crucial for data validation, text processing, and parsing. It allows programs to easily identify valid components in names, passwords, identifiers, or data fields.

Where is it used?

  • Input Validation: Ensuring that user inputs (e.g., usernames, product codes, variable names) consist only of valid alphanumeric characters.
  • Password Policies: Many password rules require at least one alphanumeric character (and often other types too).
  • Text Filtering: Removing special characters from text, leaving only letters and numbers.
  • Lexical Analysis: In compilers and interpreters, identifying valid tokens that make up keywords and identifiers.

Real-world example

When you create a username for an online account, the system often has rules like "usernames can only contain letters and numbers." This program implements the core logic for checking if each character conforms to that rule.


Algorithm

  1. Start.
  2. Get a single character (ch) from the user.
  3. Check if ch is either an alphabet (A-Z or a-z) OR a digit (0-9).
  4. If it matches either condition, ch is alphanumeric.
  5. Else, ch is not alphanumeric.
  6. Display the result.
  7. End.

Edge Cases: - Inputting more than one character (handled by taking only the first character or explicit error). - Symbols, punctuation, and whitespace: These should be correctly identified as non-alphanumeric.


Implementations

import java.util.Scanner;

public class IsAlphanumeric {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a character: ");
        char ch = scanner.next().charAt(0);

        System.out.println("Input Character: " + ch);

        // Check if the character is a letter (alphabet) or a digit
        if (Character.isLetterOrDigit(ch)) {
            System.out.println("The character '" + ch + "' is ALPHANUMERIC.");
        } else {
            System.out.println("The character '" + ch + "' is NOT alphanumeric.");
        }

        scanner.close();
    }
}
# Get a character from user
char_input = input("Enter a character: ")

# Ensure only one character is processed
if len(char_input) == 1:
    character = char_input[0]

    if character.isalnum(): # Built-in method to check if character is alphanumeric
        print(f"The character '{character}' is ALPHANUMERIC.")
    else:
        print(f"The character '{character}' is NOT alphanumeric.")
else:
    print("Please enter a single character.")
#include <stdio.h>
#include <ctype.h> // For isalnum()

int main() {
    char ch;

    printf("Enter a character: ");
    scanf(" %c", &ch); // space before %c to consume any leftover newline character

    printf("Input Character: '%c'", ch);

    if (isalnum(ch)) { // Check if character is alphanumeric
        printf("The character '%c' is ALPHANUMERIC.", ch);
    } else {
        printf("The character '%c' is NOT alphanumeric.", ch);
    }

    return 0;
}
SET SERVEROUTPUT ON;
DECLARE
  input_char  CHAR(1) := '&Enter_a_Character';
  is_alphanum BOOLEAN;
BEGIN
  DBMS_OUTPUT.PUT_LINE('Input Character: ' || input_char);

  -- Check if the character is within the ASCII range for uppercase, lowercase letters, or digits
  IF    (input_char >= 'A' AND input_char <= 'Z')
     OR (input_char >= 'a' AND input_char <= 'z')
     OR (input_char >= '0' AND input_char <= '9') THEN
    is_alphanum := TRUE;
  ELSE
    is_alphanum := FALSE;
  END IF;

  IF is_alphanum THEN
    DBMS_OUTPUT.PUT_LINE('The character "' || input_char || '" is ALPHANUMERIC.');
  ELSE
    DBMS_OUTPUT.PUT_LINE('The character "' || input_char || '" is NOT alphanumeric.');
  END IF;
END;
/

Explanation

  • Java: Uses the static method Character.isLetterOrDigit(ch) which directly checks if a character is a letter or a digit. Scanner handles character input.
  • Python: Leverages the built-in str.isalnum() method, which efficiently checks if all characters in the string are alphanumeric. It's often applied to single characters here.
  • C: Employs the isalnum() function from the <ctype.h> library, which checks if a character is an alphanumeric character. scanf(" %c", ...) reads a single character, skipping whitespace.
  • Oracle: Implemented in PL/SQL. Uses direct character range comparisons (>= and <=) for letters and digits within an IF-ELSE block. Substitution variables (&Enter_a_Character) prompt for input.

Complexity Analysis

  • Time Complexity: O(1) - The character classification operations are constant time.
  • Space Complexity: O(1) - A fixed number of variables are used.

Flowchart

graph TD
    A[Start] --> B[Get Character ch]
    B --> C{ch is A-Z OR a-z OR 0-9?}
    C -- Yes --> D[Display ALPHANUMERIC]
    C -- No --> E[Display NOT ALPHANUMERIC]
    D --> F[End]
    E --> F

Sample Dry Run

Step ch Condition (ch is letter OR ch is digit) Description
Input 'X' True User enters 'X'
Decision 'X' True Character is alphanumeric
Output - - Display "'X' is ALPHANUMERIC."
End - - Program terminates
Input '$' False User enters '$'
Decision '$' False Character is not alphanumeric
Output - - Display "'$' is NOT alphanumeric."
End - - Program terminates

Practice Problems

Easy

  • Modify the program to check if a character is a digit or a symbol.
  • Extend the program to check if an entire string is alphanumeric.

Medium

  • Write a program that filters a string, keeping only alphanumeric characters.
  • Implement a simple password validator that checks for the presence of at least one alphanumeric character.

Hard

  • Create a tokenizer that identifies alphanumeric tokens in a stream of characters, ignoring delimiters.

"The only source of knowledge is experience." - Albert Einstein