khalfella

ansi_c_pg058_ch03_ex03.c

Dec 27th, 2014
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4.  
  5. #define ST_EXP 0
  6. #define ST_BEG 1
  7. #define ST_HYP 2
  8. #define ST_RDY 3
  9. #define ST_ESC 4
  10.  
  11. #define XP_INV 0
  12. #define XP_SML 1
  13. #define XP_CAP 2
  14. #define XP_NUM 3
  15.  
  16. int
  17. is_valid_to_expand(char beg, char end) {
  18. if (beg >= 'a' && beg <= 'z' && end >= 'a' && end <= 'z')
  19. return XP_SML;
  20. else if (beg >= 'A' && beg <= 'Z' && end >= 'A' && end <= 'Z')
  21. return XP_CAP;
  22. else if (beg >= '0' && beg <= '9' && end >= '0' && end <= '9')
  23. return XP_NUM;
  24. else
  25. return XP_INV;
  26. }
  27.  
  28.  
  29. char* escape(char* s1, char* s2) {
  30. char beg, end;
  31. char c;
  32. int i, j, st, inc;
  33.  
  34. i = j = 0;
  35. st = ST_EXP;
  36.  
  37. while(c = s1[i++]) {
  38. switch(st) {
  39. case ST_EXP:
  40. if (c == '-') { /* we should escape the next expansion */
  41. st = ST_ESC;
  42. s2[j++] = c;
  43. } else {
  44. beg = c;
  45. st = ST_BEG;
  46. }
  47. break;
  48. case ST_BEG:
  49. if (c == '-') {
  50. st = ST_HYP;
  51. } else {
  52. s2[j++] = beg;
  53. beg = c;
  54. }
  55. break;
  56. case ST_HYP:
  57. end = c;
  58. st = ST_RDY;
  59. break;
  60. case ST_RDY:
  61. if (c == '-' || !is_valid_to_expand(beg, end)) {
  62. /* this expansion was escaped or invalid to expand */
  63. s2[j++] = beg;
  64. s2[j++] = '-';
  65. s2[j++] = end;
  66. s2[j++] = c;
  67. } else {
  68. inc = (beg < end)?1:((beg == end)?0:-1);
  69. s2[j++] = beg;
  70. do {
  71. beg += inc;
  72. s2[j++] = beg;
  73. } while (beg != end);
  74.  
  75. }
  76. st = ST_EXP;
  77. break;
  78. case ST_ESC:
  79. if (c == '-') {
  80. s2[j++] = c;
  81. } else {
  82. s2[j++] = c;
  83. st = ST_EXP;
  84. }
  85. break;
  86. }
  87. }
  88.  
  89.  
  90. if(st == ST_HYP) {
  91. s2[j++] = beg;
  92. s2[j++] = '-';
  93. } else if (st == ST_BEG) {
  94. s2[j++] = beg;
  95. } else if (st == ST_RDY) {
  96. if (is_valid_to_expand(beg, end)) {
  97.  
  98. inc = (beg < end)?1:((beg == end)?0:-1);
  99. s2[j++] = beg;
  100.  
  101. do {
  102. beg += inc;
  103. s2[j++] = beg;
  104. } while (beg != end);
  105.  
  106. } else {
  107. s2[j++] = beg;
  108. s2[j++] = '-';
  109. s2[j++] = end;
  110. }
  111.  
  112. } else if (st == ST_ESC) {
  113. s2[j++] = '-';
  114. }
  115.  
  116. s2[j++] = '\0';
  117. }
  118.  
  119. int
  120. main (int argc, char** argv) {
  121.  
  122. char *s2;
  123. s2 = malloc(sizeof(char) * 1000);
  124. escape(argv[1], s2);
  125. printf("%s\n", s2);
  126.  
  127. return (0);
  128.  
  129. }
Advertisement
Add Comment
Please, Sign In to add comment