Skip to content

Instantly share code, notes, and snippets.

@gpakosz

gpakosz/find.c Secret

Created April 12, 2022 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpakosz/22ff3793017d6823c65727c8ba3480b7 to your computer and use it in GitHub Desktop.
Save gpakosz/22ff3793017d6823c65727c8ba3480b7 to your computer and use it in GitHub Desktop.
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