Search code examples
cvalidationsequencealphanumeric

C code : Check whether alphanumeric value falls in specific alphanumeric range


How can I check with a C code, whether a given string falls within the start and stop range of alphanumeric values?

Eg : 
given_string = "G32"
start_string = "F00"
stop_string  = "H44"

The valid sequence here will be a set of values below:
F00 F01 F02 ------ F99
G00 G01 G02 G03 ----- G99
H00 H01 H02 H03 ----- H44

So in this case G32 falls in the range F00 - H44. Hence G32 will be valid. If we consider E99 or H45, they will not fall in the range. Hence they will be invalid.


Solution

  • Something like this should work:

    #include <stdio.h>
    #include <ctype.h>
    
    typedef struct {
        char letter;
        int number;
    } value_t;
    
    value_t get_value(char *str)
    {
        value_t result;
    
        if (strlen(str) != 3  ||    // Validate that string is 3 characters long
                !isupper(*str)  ||  // Validate that first character is uppercase
                !isdigit(str[1]  ||  !isdigit(str[2])) {  // Validate that remaining characters are digits
            printf("Invalid string!\n");
            exit(-1);
        }
        result.letter = *str;
        result.number = (str[1] - '0') * 10 + (str[2] - '0');
        return result;
    }
    
    int in_range(value_t min,value_t max,value_t val)
    {
        if (val.letter < min.letter  ||  (val.letter == min.letter  &&  val.number < min.number))
            return 0;
        if (val.letter > max.letter  ||  (val.letter == max.letter  &&  val.number > max.number))
            return 0;
        return 1;
    }
    
    int main(int argc,char *argv[])
    {
        value_t MIN = { 'F', 0 }, MAX = { 'H', 44 }, val;
    
        val = get_value(argv[1]);
        if (in_range(MIN,MAX,val))
            printf("%s is in range\n",argv[1]);
        else
            printf("%s is out of range\n",argv[1]);
    }