Skip to content

Instantly share code, notes, and snippets.

@gpakosz

gpakosz/find.c Secret

Created Apr 12, 2022
Embed
What would you like to do?
String search with memchr() and memcmp()
#include <string.h>
static char* find(const char* haystackBegin, const char* haystackEnd, const char* needleBegin, const char* needleEnd)
{
if (haystackEnd == NULL)
haystackEnd = haystackBegin + strlen(haystackBegin);
if (needleEnd == NULL)
needleEnd = needleBegin + strlen(needleBegin);
size_t haystackLength = haystackEnd - haystackBegin;
size_t needleLength = needleEnd - needleBegin;
if (haystackLength < needleLength)
return NULL;
if (needleBegin == needleEnd)
return (char*)haystackBegin;
if (needleLength == 1)
return memchr(haystackBegin, needleBegin[0], haystackLength);
while ((haystackBegin = (const char*)memchr(haystackBegin, needleBegin[0], haystackLength)) != NULL)
{
haystackLength = (size_t)(haystackEnd - haystackBegin);
if (haystackLength == 0 || haystackLength < needleLength)
return NULL;
if (haystackBegin[needleLength - 1] == needleBegin[needleLength - 1])
{
if (needleLength == 2 || memcmp(haystackBegin + 1, needleBegin + 1, needleLength - 2) == 0)
return (char*)haystackBegin;
}
++haystackBegin;
--haystackLength;
}
return NULL;
}
@fenbf
Copy link

fenbf commented Apr 14, 2022

Thanks for the suggestion! I added your code into my benchmark: https://github.com/fenbf/articles/blob/master/cpp17/searchers/searchers.cpp (there's an example test run output at the bottom)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment