d1i2p3a4k5

naive algo

Aug 14th, 2016
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.97 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int match(char [], char []);
  5.  
  6. int main() {
  7.   char a[100], b[100];
  8.   int position;
  9.  
  10.   printf("Enter some text\n");
  11.   gets(a);
  12.  
  13.   printf("Enter a string to find\n");
  14.   gets(b);
  15.  
  16.   position = match(a, b);
  17.  
  18.   if(position != -1) {
  19.     printf("Found at location %d\n", position + 1);
  20.   }
  21.   else {
  22.     printf("Not found.\n");
  23.   }
  24.  
  25.   return 0;
  26. }
  27.  
  28. int match(char text[], char pattern[]) {
  29.   int c, d, e, text_length, pattern_length, position = -1;
  30.  
  31.   text_length    = strlen(text);
  32.   pattern_length = strlen(pattern);
  33.  
  34.   if (pattern_length > text_length) {
  35.     return -1;
  36.   }
  37.  
  38.   for (c = 0; c <= text_length - pattern_length; c++)
  39.     {
  40.     position = e = c;
  41.  
  42.     for (d = 0; d < pattern_length; d++)
  43.         {
  44.       if (pattern[d] == text[e])
  45.       {
  46.         e++;
  47.       }
  48.       else {
  49.         break;
  50.       }
  51.     }
  52.     if (d == pattern_length)
  53.     {
  54.       return position;
  55.     }
  56.   }
  57.     return -1;
  58. }
Add Comment
Please, Sign In to add comment