Preview:
#include <stdio.h>
#include <ctype.h>
#include <string.h>

char keywords[10][10] = {"int", "float", "char", "if", "else", "while", "do", "return", "for", "void"};

int isKeyword(char *word) {
    for (int i = 0; i < 10; i++) {
        if (strcmp(keywords[i], word) == 0)
            return 1;
    }
    return 0;
}

void lexer(char *code) {
    int i = 0;
    char ch, buffer[20];
    int bufferIndex = 0;

    while ((ch = code[i++]) != '\0') {
        if (isalnum(ch)) {
            buffer[bufferIndex++] = ch;
        } else {
            if (bufferIndex != 0) {
                buffer[bufferIndex] = '\0';
                bufferIndex = 0;

                if (isKeyword(buffer))
                    printf("[KEYWORD => %s]\n", buffer);
                else if (isdigit(buffer[0]))
                    printf("[NUMBER => %s]\n", buffer);
                else
                    printf("[IDENTIFIER => %s]\n", buffer);
            }

            if (ch == ' ' || ch == '\n' || ch == '\t')
                continue;

            if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '=')
                printf("[OPERATOR => %c]\n", ch);

            if (ch == '(' || ch == ')' || ch == ';' || ch == '{' || ch == '}')
                printf("[SEPARATOR => %c]\n", ch);
        }
    }
}

int main() {
    char code[1000];
    printf("Enter code (e.g., int a = 10;):\n");
    fgets(code, sizeof(code), stdin);

    printf("\n--- Lexical Tokens ---\n");
    lexer(code);
    return 0;
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter