PHP 7 zend_memnstr 注解及C++测试用例

#include <iostream>
//strlen函数需要
#include <string.h>

//宏定义,没有具体任何意思,只是尽可能保留PHP7内核语法
#define EXPECTED(condition) (condition)

//函数申明
const char* zend_memnstr(const char* haystack, const char* needle, size_t needle_len, const char* end);

int main()
{

	char a[] = "abcdefg";
	char b[] = "bcd";

	char* a_p = a;
	char* end_p = a_p + strlen(a);
	const char* found = zend_memnstr(a, b, strlen(b), end_p);

	printf("%s,%s>>%s>>%d", a, b, found, found == NULL ? NULL : found - a_p);

	return 0;
}

/*
haystack 被匹配字符串指针
needle 匹配字符串指针
needle_len 匹配字符串长度
end 被匹配字符串结尾字符指针(通常字符串结尾值为'\0',ASCII值为0)
*/
const char* zend_memnstr(const char* haystack, const char* needle, size_t needle_len, const char* end)
{
	
	const char* p = haystack;
	const char ne = needle[needle_len - 1];
	ptrdiff_t off_p;
	size_t off_s;

	//匹配内容只有一个字符长度,直接用memchr内存操作函数简单比较即可
	if (needle_len == 1) {
		//end - p 指针相减获取字符长度
		return (const char*)memchr(p, *needle, (end - p));
	}

	//off_s 被匹配字符串长度
	off_p = end - haystack;
	off_s = (off_p > 0) ? (size_t)off_p : 0;


	//匹配字符串没有被匹配字符串直接返回NULL
	if (needle_len > off_s) {
		return NULL;
	}

	//匹配剩余长度没有匹配字符串长就不用匹配了
	end -= needle_len;
	//比较指针
	while (p <= end) {
		//*needle 地址值,也就是一个char
		//找到第一个char相同的地址,然后比较最后一个char,相同后才用内存函数memcmp比较
		if ((p = (const char*)memchr(p, *needle, (end - p + 1))) && ne == p[needle_len - 1]) {
			//首尾不需要比较只比较中间的即可
			if (!memcmp(needle + 1, p + 1, needle_len - 2)) {
				return p;
			}
		}

		if (p == NULL) {
			return NULL;
		}

		p++;
	}

	return NULL;
}

转载于:https://my.oschina.net/colin86/blog/3069712

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值