Untitled

 avatar
unknown
plain_text
24 days ago
1.8 kB
2
Indexable
#include <stdio.h>
#include <ctype.h>
#include <string.h>

// Function prototypes
int isIdentifier(char *str);
int isConstant(char *str);
int isOperator(char c);

int main() {
    char input[100];

    printf("Enter a string to analyze: ");
    scanf("%s", input);

    if (isIdentifier(input)) {
        printf("'%s' is an Identifier.\n", input);
    } else if (isConstant(input)) {
        printf("'%s' is a Constant.\n", input);
    } else if (strlen(input) == 1 && isOperator(input[0])) {
        printf("'%s' is an Operator.\n", input);
    } else {
        printf("'%s' is not recognized.\n", input);
    }

    return 0;
}

// Function to check if a string is an identifier
int isIdentifier(char *str) {
    if (!isalpha(str[0]) && str[0] != '_') {
        return 0; // Must start with a letter or underscore
    }

    for (int i = 1; i < strlen(str); i++) {
        if (!isalnum(str[i]) && str[i] != '_') {
            return 0; // Must contain only alphanumeric characters or underscores
        }
    }

    return 1; // Valid identifier
}

// Function to check if a string is a constant
int isConstant(char *str) {
    int i = 0;

    // Optional sign for numeric constants
    if (str[i] == '+' || str[i] == '-') {
        i++;
    }

    int hasDigits = 0;

    // Check for digits
    for (; i < strlen(str); i++) {
        if (!isdigit(str[i])) {
            return 0; // Invalid if a non-digit character is found
        }
        hasDigits = 1;
    }

    return hasDigits; // Valid if there were digits
}

// Function to check if a character is an operator
int isOperator(char c) {
    char operators[] = "+-*/%=&|<>!"; // List of operators
    for (int i = 0; i < strlen(operators); i++) {
        if (c == operators[i]) {
            return 1; // Valid operator
        }
    }
    return 0; // Not an operator
}
Leave a Comment