Tuesday 24 January 2012

Pattern Matching

c program for pattern matching, pattern matching in c

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



#include<stdio.h>
#include<conio.h>

int match(char*, char*);

void main()
{
    char a[100], b[100];
    int position;
    clrscr();
    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");
    getch();
}

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;
}

No comments:

Post a Comment