Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define ST_EXP 0
- #define ST_BEG 1
- #define ST_HYP 2
- #define ST_RDY 3
- #define ST_ESC 4
- #define XP_INV 0
- #define XP_SML 1
- #define XP_CAP 2
- #define XP_NUM 3
- int
- is_valid_to_expand(char beg, char end) {
- if (beg >= 'a' && beg <= 'z' && end >= 'a' && end <= 'z')
- return XP_SML;
- else if (beg >= 'A' && beg <= 'Z' && end >= 'A' && end <= 'Z')
- return XP_CAP;
- else if (beg >= '0' && beg <= '9' && end >= '0' && end <= '9')
- return XP_NUM;
- else
- return XP_INV;
- }
- char* escape(char* s1, char* s2) {
- char beg, end;
- char c;
- int i, j, st, inc;
- i = j = 0;
- st = ST_EXP;
- while(c = s1[i++]) {
- switch(st) {
- case ST_EXP:
- if (c == '-') { /* we should escape the next expansion */
- st = ST_ESC;
- s2[j++] = c;
- } else {
- beg = c;
- st = ST_BEG;
- }
- break;
- case ST_BEG:
- if (c == '-') {
- st = ST_HYP;
- } else {
- s2[j++] = beg;
- beg = c;
- }
- break;
- case ST_HYP:
- end = c;
- st = ST_RDY;
- break;
- case ST_RDY:
- if (c == '-' || !is_valid_to_expand(beg, end)) {
- /* this expansion was escaped or invalid to expand */
- s2[j++] = beg;
- s2[j++] = '-';
- s2[j++] = end;
- s2[j++] = c;
- } else {
- inc = (beg < end)?1:((beg == end)?0:-1);
- s2[j++] = beg;
- do {
- beg += inc;
- s2[j++] = beg;
- } while (beg != end);
- }
- st = ST_EXP;
- break;
- case ST_ESC:
- if (c == '-') {
- s2[j++] = c;
- } else {
- s2[j++] = c;
- st = ST_EXP;
- }
- break;
- }
- }
- if(st == ST_HYP) {
- s2[j++] = beg;
- s2[j++] = '-';
- } else if (st == ST_BEG) {
- s2[j++] = beg;
- } else if (st == ST_RDY) {
- if (is_valid_to_expand(beg, end)) {
- inc = (beg < end)?1:((beg == end)?0:-1);
- s2[j++] = beg;
- do {
- beg += inc;
- s2[j++] = beg;
- } while (beg != end);
- } else {
- s2[j++] = beg;
- s2[j++] = '-';
- s2[j++] = end;
- }
- } else if (st == ST_ESC) {
- s2[j++] = '-';
- }
- s2[j++] = '\0';
- }
- int
- main (int argc, char** argv) {
- char *s2;
- s2 = malloc(sizeof(char) * 1000);
- escape(argv[1], s2);
- printf("%s\n", s2);
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment