You are here

C program for pattern matching

Pattern matching in C: C program to check if a string is present in an another string, for example, the string "programming" is present in the string "C programming". If it's present, then its location (i.e. at which position it's present) is printed. We create a function match which receives two character arrays and returns the position if matching occurs otherwise returns -1. We are implementing naive string search algorithm in this program.

C program

#include <stdio.h>
#include <string.h>

int match(char [], char []);

int main() {
  char a[100], b[100];
  int position;

  printf("Enter some text\n");
  gets(a);

  printf("Enter a string to find\n");
  gets(b);

  position = match(a, b);

  if (position != -1) {
    printf("Found at location: %d\n", position + 1);
  }
  else {
    printf("Not found.\n");
  }

  return 0;
}

int match(char text[], char pattern[]) {
  int c, d, e, text_length, pattern_length, position = -1;

  text_length    = strlen(text);
  pattern_length = strlen(pattern);

  if (pattern_length > text_length) {
    return -1;
  }

  for (c = 0; c <= text_length - pattern_length; c++) {
    position = e = c;

    for (d = 0; d < pattern_length; d++) {
      if (pattern[d] == text[e]) {
        e++;
      }
      else {
        break;
      }
    }
    if (d == pattern_length) {
      return position;
    }
  }

  return -1;
}

Output of program:
Pattern matching C program

Download Pattern matching program.

C program for pattern matching using pointers

#include<stdio.h>

int match(char*, char*);

int main()
{
   char a[100], b[100];
   int position;
   
   printf("Enter some text\n");
   gets(a);
       
   printf("Enter a string to find\n");
   gets(b);
   
   position = match(a, b);
   
   if(position!=-1)
      printf("Found at location %d\n", position+1);
   else
      printf("Not found.\n");
     
   return 0;  
}

int match(char *a, char *b)
{
   int c;
   int position = 0;
   char *x, *y;
   
   x = a;
   y = b;
   
   while(*a)
   {
      while(*x==*y)
      {
         x++;
         y++;
         if(*x=='\0'||*y=='\0')
            break;        
      }  
      if(*y=='\0')
         break;
         
      a++;
      position++;
      x = a;
      y = b;
   }
   if(*a)
      return position;
   else  
      return -1;  
}