Advertisement
cmiN

sablon

Apr 10th, 2011
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. #include <cstdio>
  2. #include <string.h>
  3.  
  4. const int LEN = 1001;
  5. FILE *fin, *fout;
  6. char temp[LEN], sab[LEN], str[LEN];
  7.  
  8.  
  9. // transform a template like "ab**c****" into "ab*c*"
  10. void safety()
  11. {
  12.     char *a = temp, *b, *c = sab;
  13.     while( (b = strstr(a, "**")) ) {    // find first occurence (b) of more than one '*'
  14.         memcpy(c, a, b - a + 1);        // copy everything up to b to c
  15.         c += b - a + 1;
  16.         a = b;
  17.         while(*(++a) == '*');           // discard remaining '*' characters from b (now equal to a)
  18.     }
  19.     strcpy(c, a);                       // copy remaining characters
  20.     strcat(c, " ");                     // ' ' signals the end of a string (it's different from '/0')
  21. }
  22.  
  23. // does the template sab match the str?
  24. bool isStrMatch()
  25. {
  26.     int i = 0, L;
  27.     strcpy(temp, sab);                  // we'll later modify the contents of m
  28.     char *m = temp, *w = str;           // m = match (or mask), w = word
  29.  
  30.     // match the start of the string
  31.     while ( (m[i] == w[i] || m[i] == '?') && m[i] && w[i] ) ++i;
  32.  
  33.     if (!m[i] && !w[i]) return true;    // no '*' in m and strigs match perfectly
  34.     else if (m[i] != '*') return false; // mismatch occured
  35.  
  36.     // initially we presumed m was in the form of (S0*S1*S2...*Sn)
  37.     // we matched S0 so add i to m to make it in the form of "*S1*S2*S3...*Sn"
  38.     // where S1, S2 are strings of one or more letters and Sn (is)/(ends in) ' '
  39.     m += i, w += i;
  40.  
  41.     while(*m && *w) {
  42.         m++;                            // m is now S1*S2...*Sn
  43.         char *p = strchr(m, '*');
  44.         if (p) *p = '\0';
  45.  
  46.         // m is now "S1", m + 1 is "S2...*Sn"
  47.         if ( !(w = strstr(w, m)) ) return false;
  48.         i = strlen(m);
  49.         m += i, w += i;
  50.         if (p) *p = '*';                       // restore p's value, otherwise *m will fail
  51.     };
  52.     if (*w) return false;
  53.     return true;
  54. }
  55.  
  56. int main()
  57. {
  58.     int nr;
  59.     fin = fopen("sablon.in", "rt");
  60.     fout = fopen("sablon.out", "wt");
  61.     fscanf(fin, "%d", &nr);
  62.     fscanf(fin, "%s", temp);
  63.     safety();
  64.     for (int i = 1; i <= nr; i++) {
  65.         fscanf(fin, "%s", str);
  66.         strcat(str, " ");               // see safety()
  67.         if (isStrMatch()) fprintf(fout, "%d\n", i);
  68.     }
  69.     fclose(fin);
  70.     fclose(fout);
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement