C语言实现的带通配符的字符串匹配

RT

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

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

没办法  自己写个吧。。。

C语言的。。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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;
}


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值