Sunday, July 8, 2007

Write a C program which does wildcard pattern matching algorithm.

Here is an example C program...


#include < stdio.h >
#define TRUE 1
#define FALSE 0

int wildcard(char *string, char *pattern);

int main()
{
char *string = "hereheroherr";
char *pattern = "*hero*";

if(wildcard(string, pattern)==TRUE)
{
printf("\nMatch Found!\n");
}
else
{
printf("\nMatch not found!\n");
}
return(0);
}

int wildcard(char *string, char *pattern)
{
while(*string)
{
switch(*pattern)
{
case '*': do {++pattern;}while(*pattern == '*');
if(!*pattern) return(TRUE);
while(*string){if(wildcard(pattern,string++)==TRUE)return(TRUE);}
return(FALSE);
default : if(*string!=*pattern)return(FALSE); break;
}
++pattern;
++string;
}

while (*pattern == '*') ++pattern;
return !*pattern;
}

5 comments:

Vikash Mehta said...

Here is the working code:-

#include
#define TRUE 1
#define FALSE 0

int wildcard(char *string, char *pattern);

int main()
{
char *string = "iereherojerr";
char *pattern = "*hero*";

if(wildcard(string, pattern)==TRUE)
{
printf("\nMatch Found!\n");
}
else
{
printf("\nMatch not found!\n");
}
return(0);
}


int wildcard(char *string, char *pattern)
{
while(*string)
{
switch(*pattern)
{
case '*': do {
++pattern;
} while(*pattern == '*');

if(!*pattern)
{
return(TRUE);
}

while(*string != '\0')
{
if(*pattern != *string) string++;
else break;

}
/*while(*pattern != *string)
{
if(!*pattern) return FALSE;
string++;
}*/

// while(*string)
{
if(wildcard(string++,pattern++)==TRUE)
return(TRUE);
}

return(FALSE);
default :
while(*pattern != '\0')
{
if(*pattern == '*')
{
if(wildcard(string, pattern) == TRUE)
return (TRUE);

}

if(*string !=*pattern)
{
return(FALSE);
}
pattern++;
string++;
}
return TRUE;
break;
}
++pattern;
++string;
}

while (*pattern == '*') ++pattern;
return !*pattern;
}

AaronMiller said...

http://codepad.org/vdkJgqw6

Use const to indicate your function will not write to the string.

Recursion is unnecessary.

Anonymous said...

wildcard("ab*d", "abcdd") returns false, but I would expect true. The same applies to the code found at the codepad link.

See wikipedia's definition of wildcard: https://en.wikipedia.org/wiki/Wildcard_character

Anonymous said...

I really love your website.. Excellent colors & theme.

Did you develop this website yourself? Please reply
back as I'm wanting to create my own personal website and would like to learn where you got this from or just what the theme is called. Appreciate it!

Feel free to visit my site http://Master104Finance.com/forum/profile.php?id=1689

Larry Villa said...

Hello mate, great blog post