linux如何处理通配符c语言,C语言实现的带通配符的字符串匹配

RT

就是输入str1 是要被匹配的字符串,str2是带*、?的匹配规则,符合返回1  否则0

异常简单的函数,想着网上应该有吧,不想自己写搜个就拿来用吧,谁知道居然搜不到

没办法  自己写个吧。。。

C语言的。。

#include

#include

#include

char *my_strstr(const char * str1,const char * str2, int len)

{

char *tmp2,*tmp1 = (char *)malloc(len);

memcpy(tmp1,str2,len);

tmp2 = strstr(str1,tmp1);

free(tmp1);

return tmp2;

}

int _m(char * str1,char * str2)

{

char *pos=str1,*pos1=str2,*pos2=str2;

char *tmp;

while(1)

switch(*pos1)

{

case '*':

pos1++;

pos2++;

while(*pos2 != '*' && *pos2 != '?' && *pos2 != '\0')

pos2++;

if (pos2 != pos1)

{

tmp = my_strstr(pos,pos1,pos2-pos1);

if(tmp != NULL)

{

pos = tmp+ (pos2-pos1);

pos1 = pos2;

}

else

return 0;

}

break;

case '?':

pos1++;

pos2++;

if(*pos!='\0')

pos++;

else

return 0;

break;

case '\0':

return 1;

break;

default:

while(*pos2 != '*' && *pos2 != '?' && *pos2 != '\0')

pos2++;

//tmp = my_strstr(pos,pos1,pos2-pos1);

//if(tmp != NULL && tmp == pos)

if(!memcmp(pos,pos1,pos2-pos1))

{

pos += pos2-pos1;

pos1 = pos2;

}

else

return 0;

break;

}

return 0;

}

int main(void)

{

printf("%d \n",_m("hello world","h?*wo*l?*"));

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C语言中字符串*通配符的匹配过程的示例代码: ```c #include <stdio.h> #include <string.h> int match(char *pattern, char *text) { // 如果 pattern 和 text 都为空,则匹配成功 if (*pattern == '\0' && *text == '\0') { return 1; } // 如果 pattern 为空但 text 不为空,则匹配失败 if (*pattern == '\0') { return 0; } // 如果 pattern 的第二个字符是 *,则有两种情况: if (*(pattern + 1) == '*') { // 1. * 匹配 0 个字符 if (match(pattern + 2, text)) { return 1; } // 2. * 匹配 1 个或多个字符 while (*text != '\0' && (*pattern == '.' || *pattern == *text)) { if (match(pattern + 2, text + 1)) { return 1; } text++; } return 0; } // 如果 pattern 的第二个字符不是 *,则只需匹配第一个字符是否相同 if (*text != '\0' && (*pattern == '.' || *pattern == *text)) { return match(pattern + 1, text + 1); } return 0; } int main() { char pattern[] = "a*b*c"; char text1[] = "abc"; char text2[] = "aabbcc"; char text3[] = "ac"; printf("%s\t%s\t%d\n", pattern, text1, match(pattern, text1)); printf("%s\t%s\t%d\n", pattern, text2, match(pattern, text2)); printf("%s\t%s\t%d\n", pattern, text3, match(pattern, text3)); return 0; } ``` 输出结果为: ``` a*b*c abc 1 a*b*c aabbcc 1 a*b*c ac 0 ``` 其中,函数 match 的参数 pattern 和 text 分别表示要匹配的模式和文本,函数返回值表示是否匹配成功。在函数中,使用递归的方式匹配字符串,考虑了模式中的通配符 *,并且实现通配符 * 匹配 0 个、1 个或多个字符的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值