-
-
Save gpakosz/22ff3793017d6823c65727c8ba3480b7 to your computer and use it in GitHub Desktop.
String search with memchr() and memcmp()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)