本例实现通配符 * 的功能,不支持*在字符串的末尾, 仅提供思路,函数仅做简单单元测试。 如有使用,还请自己进行修改
// str1: 待匹配字符串 // str2: 带通配符字串 int wildcard_match(char *str1, char *str2) {if(str1 == NULL || str2 == NULL)return 0 ;int len1 = strlen(str1);int len2 = strlen(str2);char *tmp_str = str2 ;int tmp_len = len2 ;int location = 0 ;int match_flag = 0 ;int i = 0 ;// 查询 str2中是否含有通配符 *, 两种方法,从前、后分别找*/* while(tmp_len--) {if(tmp_str[tmp_len] == '*'){location = tmp_len+1 ; // +1 for judge when the * be the first letter.break ;}} */while(i<tmp_len) {if(tmp_str[i] == '*') {location = i+1 ; // 加1 是为了处理 *出现在开头的情况。 在开头的话,location == 0;break ;}i++ ;}// Get the *char *tmp_str1 = str1 ;char *tmp_str2 = str2 ;// 如果找到location 不为0 ,那么就进行通配符匹配。if(location) {location -= 1;// if location is 0 , the strncmp function will return 0 too .//现对比* 前的字符串, 如果前面都没匹配,直接返回未匹配结果if(!strncmp(str1, str2, location)) {tmp_len = len2 - location ;tmp_str1 += len1 ;tmp_str2 += len2 ;//在匹配*后的字符串,从尾往前找。while(--tmp_len && (*tmp_str1 == *tmp_str2)){tmp_str1 -- ;tmp_str2 -- ;}match_flag = tmp_len?0:1 ;} } return match_flag ; }