1

I need to compare two strings, one of which uses "?" wildcard. If the pattern is e?lo and string is hello, the comparison function should return true. I was thinking of using a recursive method, but it apparently only works when the matching is cover the entire input string. What is the correct solution?

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAX 100

bool WildCmp(char *pattern, char *string);

int main(void)
{
  char pattern[MAX];
  char string[MAX];

  printf("What is the pattern?\n");
  fgets(pattern, MAX, stdin);
  printf("What is the string?\n");
  fgets(string, MAX, stdin);


  if(WildCmp(pattern, string))
    printf("Match Found\n");
  else
    printf("Match Not Found");

  return 0;
}


bool WildCmp(char *pattern, char *string)
{
  if (*pattern=='\0' && *string=='\0')
    return true;

  if (*pattern != '\0' && *pattern != *string)
    return WildCmp(pattern, string+1);

  if (*pattern=='?' || *pattern==*string)
    return WildCmp(pattern+1,string+1);

  if (*pattern=='*')
    return WildCmp(pattern+1,string) || WildCmp(pattern,string+1);

  return false;
}
mutatal
  • 71
  • 3
  • Is this a homework question, or something like that? Otherwise I'd suggest just using a regular expression, e.g. http://stackoverflow.com/questions/1085083/regular-expressions-in-c-examples If it is a homework question I can give you a few pointers. – struthersneil Apr 04 '17 at 15:20
  • Thanks. It is a homework question. – mutatal Apr 04 '17 at 15:23
  • Ok. Did they specifically ask for a solution that used recursion? – struthersneil Apr 04 '17 at 15:27
  • No. no special requirements. – mutatal Apr 04 '17 at 15:29
  • Ok, in that case I would keep it very simple. Have a function that can compare a given string (a given char *) to the pattern. So answer the question 'does the string starting here match the pattern?' Then walk through the possible starting positions of the string from zero up to the end of the string minus the pattern length (with an early out if the string is shorter than the pattern) calling your comparison function with a new starting position each time. If you need to support a * wildcard then things get trickier. – struthersneil Apr 04 '17 at 15:36
  • Thanks, I get it now. – mutatal Apr 04 '17 at 15:42

0 Answers0