#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