String 如何在C中部分比较两个带通配符的字符串?

String 如何在C中部分比较两个带通配符的字符串?,string,pattern-matching,wildcard,String,Pattern Matching,Wildcard,我需要比较两个字符串,其中一个使用“?”通配符。 如果模式为e?lo,字符串为hello,则比较函数应返回true。 我曾考虑使用递归方法,但它显然只在匹配覆盖整个输入字符串时才起作用。正确的解决方案是什么 #include <stdio.h> #include <stdbool.h> #include <string.h> #define MAX 100 bool WildCmp(char *pattern, char *string); int mai

我需要比较两个字符串,其中一个使用“?”通配符。 如果模式为
e?lo
,字符串为
hello
,则比较函数应返回true。 我曾考虑使用递归方法,但它显然只在匹配覆盖整个输入字符串时才起作用。正确的解决方案是什么

#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;
}
#包括
#包括
#包括
#定义最大值100
boolwildcmp(字符*模式,字符*字符串);
内部主(空)
{
字符模式[MAX];
字符串[MAX];
printf(“模式是什么?\n”);
fgets(图案、最大值、标准尺寸);
printf(“字符串是什么?\n”);
fgets(字符串、最大值、标准输入);
if(WildCmp(模式、字符串))
printf(“找到匹配项\n”);
其他的
printf(“未找到匹配项”);
返回0;
}
boolwildcmp(字符*模式,字符*字符串)
{
如果(*模式=='\0'&&&*字符串=='\0')
返回true;
如果(*模式!='\0'&&&&*模式!=*字符串)
返回WildCmp(模式,字符串+1);
如果(*模式=='?'| |*模式==*字符串)
返回WildCmp(模式+1,字符串+1);
如果(*模式=='*'))
返回WildCmp(模式+1,字符串)| | WildCmp(模式,字符串+1);
返回false;
}

这是家庭作业问题还是类似的问题?否则我建议只使用正则表达式,例如,如果这是一个家庭作业问题,我可以给你一些提示。谢谢。这是一个家庭作业问题。他们有没有特别要求使用递归的解决方案?没有。没有特殊要求。好的,在这种情况下,我会保持它非常简单。有一个函数可以将给定的字符串(给定的字符*)与模式进行比较。因此,回答“从这里开始的字符串是否与模式匹配?”然后遍历字符串的可能起始位置,从零到字符串末尾减去模式长度(如果字符串短于模式,则提前退出),每次调用具有新起始位置的比较函数。如果你需要支持一个*通配符,那么事情就变得更棘手了。这是一个家庭作业问题,还是类似的问题?否则我建议只使用正则表达式,例如,如果这是一个家庭作业问题,我可以给你一些提示。谢谢。这是一个家庭作业问题。他们有没有特别要求使用递归的解决方案?没有。没有特殊要求。好的,在这种情况下,我会保持它非常简单。有一个函数可以将给定的字符串(给定的字符*)与模式进行比较。因此,回答“从这里开始的字符串是否与模式匹配?”然后遍历字符串的可能起始位置,从零到字符串末尾减去模式长度(如果字符串短于模式,则提前退出),每次调用具有新起始位置的比较函数。如果您需要支持*通配符,那么事情会变得更棘手。