// Locate the first occurrence of a multi-part substring in a string. Substring is composed of s2 and s3.
const char* mpstrstr(const char* s1, const char* s2, const char* s3) {
const char* sp; // String / haystack pointer.
const char* pos = s1; // Current search start position.
const char* n; // Needle pointer.
// Sanity check.
if (!*s1 || !*s2 || !*s3)
return NULL;
// Find needle char in string.
while ( ( pos = sp = std::strchr(pos, *s2) ) ) {
// Point or re-point needle.
n = s2;
// Try to compare the strings.
while (*sp && *n && *sp == *n) {
sp++;
n++;
}
// Match. Needle ended, but still room in string to match s3.
if (*sp && !*n) {
// Save length of s2
std::size_t s2_size = n - s2;
// Point needle to next string.
n = s3;
// Try to compare the strings.
while (*sp && *n && *sp == *n) {
sp++;
n++;
}
// Ok this is a match.
// Return a pointer to the first character in s1 that matched.
if (!*n)
return sp - ( (n - s3) + s2_size );
}
pos++; // Increment search start position.
}
return NULL;
}