Chapter 10 · Simulation

String Parsing: Finite State Machine

← Chapter 10

Rule: the first character must be a letter or an underscore.

State Diagram

letter, _ digit, other, end letter, digit, _ end other START IDENT ACCEPT REJECT

Transition Table

Current StateCharacter ClassNext State
STARTLETTERIDENT
STARTUNDERSCOREIDENT
STARTDIGITREJECT
STARTOTHERREJECT
IDENTLETTERIDENT
IDENTDIGITIDENT
IDENTUNDERSCOREIDENT
IDENTOTHERREJECT

    String Parsing: Finite State Machine

    An identifier is validated step by step using states, character classes and explicit transitions.

    How to use

    • Type a sample input (up to 24 characters) and press Load Input.
    • Step reads one character, Auto Play runs until the machine accepts or rejects, Reset reloads the input.
    • Yellow cell: the next character to read. Green cells: characters already read. Red cell: the character that caused the rejection.
    • The state diagram and the transition table highlight the transition just taken.

    The identifier rule

    An identifier starts with a letter or an underscore; the remaining characters are letters, digits or underscores. Each character is first mapped to a character class (LETTER, DIGIT, UNDERSCORE, OTHER); the next state depends only on the current state and this class.

    • START: nothing has been read yet. LETTER or UNDERSCORE moves to IDENT; DIGIT or OTHER rejects.
    • IDENT: a valid identifier has been read so far. LETTER, DIGIT and UNDERSCORE keep the machine in IDENT; OTHER rejects.
    • When the input ends, the string is accepted only if the machine is in IDENT; empty input is rejected.

    Why a state machine?

    Lexers in compilers and interpreters recognize identifiers, numbers and keywords with exactly this kind of deterministic finite automaton: one table lookup per character, no backtracking.

    Complexity

    O(n) time for an input of length n (one transition per character) and O(1) extra memory; the transition table has |states| × |classes| entries.