Spread the love

Write a C program which does wildcard pattern matching algorithm

Given two strings where first string may contain wild card characters and second string is a normal string. Write a function that returns true if the two strings match. The following are allowed wild card characters in first string.

* –> Matches with one or more instances of any character or set of characters.
? –> Matches with any single character.

For example, here “f?rmc*” matches with “firmcodes” string. Because it use two ‘*’  characters and single ? which indicates set of characters unknown and single character not known respectively.

 

#include <stdio.h>
#include <stdbool.h>
 
bool WildCmp(char *pattern, char *string);
 
int main()
{
	if(WildCmp("f?rmc*","firmcodes"))
	{
			printf("! Match Found");
	}
	else
	{
			printf("! Match Not Found");
	}
	
	return 0;
}


bool WildCmp(char *pattern, char *string)
{
	if(*pattern=='\0' && *string=='\0')		// Check if string is at end or not.
		return true;
		
	if(*pattern=='?' || *pattern==*string)		//Check for single character missing or match
		return WildCmp(pattern+1,string+1);
		
	if(*pattern=='*')
		return WildCmp(pattern+1,string) || WildCmp(pattern,string+1);		// Check for multiple character missing
		
	return false;
}

 

Output

Write a C program which does wildcard pattern matching algorithm

Suggested Reading

  1. Write a C program to reverse the words in a sentence in place
  2. Write your own trim() or squeeze() function to remove the spaces from a string
  3. Write a C program to reverse the string without using strrev() ?

If you like this Article, then don’t forget to Click on Social likes buttons.