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.
CodePudding user response:
You can use strcmp. From the 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.
here is some illustrative code
#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;
}
Output:
String in range
String NOT in range
String NOT in range
String in range
String in range
String in range
Things could change depending on string length, case, etc.
CodePudding user response:
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]);
}
