forked from jhpy1024/CProgrammingLanguageExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise_3-3.c
88 lines (74 loc) · 1.89 KB
/
exercise_3-3.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <stdio.h>
#include <stdbool.h>
enum
{
NO_OPERAND = '\0',
OPERATOR = '-'
};
enum state
{
NONE,
IN_EXPANSION
};
bool is_operand_valid(char c)
{
return (c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z');
}
/* Assumes that expanded is large enough. */
void expand(char shorthand[], char expanded[])
{
char left_operand = NO_OPERAND;
char right_operand = NO_OPERAND;
int state = NONE;
int expanded_index = 0;
for (int i = 0; shorthand[i] != '\0'; ++i)
{
char current_char = shorthand[i];
switch (state)
{
case NONE:
if (is_operand_valid(current_char))
{
left_operand = current_char;
}
else if (current_char == OPERATOR)
{
if (left_operand != NO_OPERAND)
{
state = IN_EXPANSION;
}
else
{
expanded[expanded_index++] = current_char;
}
}
break;
case IN_EXPANSION:
if (is_operand_valid(current_char))
{
right_operand = current_char;
state = NONE;
for (char c = left_operand; c <= right_operand; ++c)
{
expanded[expanded_index++] = c;
}
left_operand = NO_OPERAND;
right_operand = NO_OPERAND;
}
break;
default:
break;
}
}
expanded[expanded_index] = '\0';
}
int main()
{
char shorthand[] = "-a-z0-9-";
char expanded[1000] = { 0 };
expand(shorthand, expanded);
printf("%s\n", expanded);
return 0;
}