shubham johar
shubham johar

Reputation: 278

C- pattern matching

I am trying to write a program that receives input infinitely and whenever an input sequence matches a given pattern it should print that a match has been found and continue searching for other occurrences of the pattern I managed just to code this

   #include<stdio.h>
    #include<string.h>
    int main(){
      char ch;
      char pattern[4]="1234";
      int i=0;
      while(1){
        scanf(" %c",&ch);
        if(ch==pattern[i]){
          i+=1;
        } else {
            i = 0;
        }
        if (i == 4) {
            printf("match found!\n");
            i = 0;
        }
        //printf("%c",ch);
      }
      return 0;
    }

The problem is that this code doesn't handle repetion cases like 11234 .

my other approach uses buffering, that has some error

#include<stdio.h>
#include<string.h>
int main(){
  char ch;
  char pattern[4]="1234";
  char buf[4] = "";
  int i=0;
  while(1){
    scanf(" %c",&ch);
    buf[i%4]=ch;
    i++;
    if(strcmp(pattern,buf)==0){
      printf("Match found");
    }
  }
  return 0;
}

Help me fix the problem

Upvotes: 1

Views: 1558

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

The problem is that when a given character, let's say the second 1 entered, does not fulfill the if(ch==pattern[i])-condition, you "reset" the pattern but you will not check this already entered 1 for the beginning of the "new" pattern check. So write the following:

else {
   i = (ch==pattern[0]) ? 1 : 0;

Upvotes: 2

Related Questions