3.3.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <stdio.h>
  2. #include <assert.h>
  3. int expand(char* ,char*,int );
  4. void expandRange(int , char , char , char* ,int);
  5. int clear(char* c, int count);
  6. #define MAGIC_1 2048
  7. int main()
  8. {
  9. char b[MAGIC_1];
  10. clear(b,MAGIC_1);
  11. expand("lol what is this bullshit a-z",b,1);
  12. printf("\n%s\n",b);
  13. clear(b,MAGIC_1);
  14. expand("lol what is this bullshit a-c",b,1);
  15. printf("\n%s\n",b);
  16. clear(b,MAGIC_1);
  17. expand("lol what is this bullshit a-b-c",b,1);
  18. printf("\n%s\n",b);
  19. clear(b,MAGIC_1);
  20. expand("lol what is this bullshit 0-a",b,0);
  21. printf("\n%s\n",b);
  22. clear(b,MAGIC_1);
  23. return 0;
  24. }
  25. int clear(char* c, int count)
  26. {
  27. for (int i=0; i<count;i++)
  28. {c[i]=0;}
  29. return 0;
  30. }
  31. /* in string s1 if a - is detected.
  32. 1) check before the -.
  33. if it's a space, treat it like normal
  34. if it's not a space, treat this as the beginning of the range
  35. check after the -
  36. expand for one until the other.
  37. if it's the end of a range treat it like normal
  38. /* a-z turns to abcdef...z */
  39. /* case and digits allowed */
  40. /* and be prepared to handle cases like a-b-c and a-z0-9 and -a-z. */
  41. /* Arrange that a leading or trailing - is taken literally. */
  42. /* s2 should be initialized to 0*/
  43. int expand(char* s1,char* s2, int largerange)
  44. {
  45. // s2 has to be big enough
  46. if (s1 == 0)
  47. {
  48. s2=0;
  49. return -1;
  50. }
  51. for (int i=0,j=0,last_match=0;s1[i]!=0;i++,j++)
  52. {
  53. switch(s1[i])
  54. {
  55. case '-':
  56. if ((i!=0) && (last_match!=(i-1)) && (s1[i+1]!=0)) // we're good to expand
  57. {
  58. //we should be checking for digits/alphanumerics here somewhere
  59. int count = (int)(s1[i+1]-s1[i-1])+1;
  60. char newc[count] ;
  61. expandRange(count,s1[i-1],s1[i+1],newc,largerange);
  62. for (int k=1;k<count; k++) //we don't need the first one, we've already got it
  63. {
  64. s2[j]=newc[k];
  65. j++;
  66. }
  67. j--; // for some reason this goes one to far.
  68. last_match=i+1;
  69. i++; //gets rid of -
  70. continue;
  71. }
  72. else if (last_match ==(i-1)) //ie we just finished one
  73. {
  74. s2[j]=s1[i];
  75. continue;
  76. }; //drop through to default
  77. default:
  78. s2[j]=s1[i];
  79. }
  80. }
  81. return 0;
  82. }
  83. void expandRange(int count, char c1, char c2, char* newc, int largerange)
  84. {
  85. if (largerange)
  86. if (c1 >= 'a')
  87. assert (c2 <= 'z');
  88. else if (c1 >= 'A')
  89. assert (c2 <= 'Z');
  90. else if (c1 >= '0')
  91. assert (c2 <= '9');
  92. for (int i =0, j=(int)c1, end=(int)c2; i < count; i++, j++)
  93. newc[i]=j;
  94. }