65.9K
CodeProject 正在变化。 阅读更多。
Home

通配符字符串比较 (globbing)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.90/5 (77投票s)

2001年5月2日

viewsIcon

1324836

将字符串与通配符字符串进行匹配,例如 "*.*" 或 "bl?h.*" 等。这对于文件通配符匹配或匹配主机掩码非常有用。

用法

这是一个快速、轻量级且简单的模式匹配函数。

if (wildcmp("bl?h.*", "blah.jpg")) {
  //we have a match!
} else {
  //no match =(
}

函数

int wildcmp(const char *wild, const char *string) {
  // Written by Jack Handy - jakkhandy@hotmail.com
  const char *cp = NULL, *mp = NULL;

  while ((*string) && (*wild != '*')) {
    if ((*wild != *string) && (*wild != '?')) {
      return 0;
    }
    wild++;
    string++;
  }

  while (*string) {
    if (*wild == '*') {
      if (!*++wild) {
        return 1;
      }
      mp = wild;
      cp = string+1;
    } else if ((*wild == *string) || (*wild == '?')) {
      wild++;
      string++;
    } else {
      wild = mp;
      string = cp++;
    }
  }

  while (*wild == '*') {
    wild++;
  }
  return !*wild;
}
© . All rights reserved.