C代码:检查字母数字值是否落在特定的字母数字范围内

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

如何使用 C 代码进行检查, 给定的字符串是否在字母数字值的开始和结束范围内?

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

所以在这种情况下,G32 位于 F00 - H44 范围内。因此 G32 将有效。 如果我们考虑E99或H45,它们将不在该范围内。因此它们将无效。

您可以使用 strcmp。来自 manpage

strcmp() returns an integer indicating the result of the comparison, as follows:
• 0, if the s1 and s2 are equal;
• a negative value if s1 is less than s2;
• a positive value if s1 is greater than s2.

这是一些说明性代码

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool StrInRange(const char* start, const char* end, const char* testStr)
{
    // start is "F00", so if this comparison returns 0 or negative,
    // testStr is equal or "bigger" than testStr
    bool aboveStart = strcmp(start, testStr) <= 0;
    // end is "H44", so if this comparison returns 0 or positive,
    // testStr is equal or "smaller" than testStr
    bool belowEnd = strcmp(end, testStr) >= 0;
    // if both are true, testStr is within range.
    return aboveStart && belowEnd;
}

int main(void)
{
    const char* START_STR = "F00";
    const char* END_STR = "H44";

    const char* testStrs[] = {"G32", "E99", "H45", "F00", "H44", "G00"};

    for (size_t i=0; i< sizeof(testStrs)/sizeof(*testStrs); i++)
    {
        if (StrInRange(START_STR, END_STR, testStrs[i]) == true)
        {
            printf("String in range\n");
        }
        else
        {
            printf("String NOT in range\n");
        }
    }

    return 0;
}

输出:

String in range
String NOT in range
String NOT in range
String in range
String in range
String in range

Demonstration

情况可能会根据字符串长度、大小写等发生变化。

像这样的东西应该可以工作:

#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]);
}