strstr() for a string that is NOT null-terminated

user541686 picture user541686 · Dec 21, 2011 · Viewed 16.8k times · Source

How do I do the in-place equivalent of strstr() for a counted string (i.e. not null-terminated) in C?

Answer

Tim Cooper picture Tim Cooper · Dec 21, 2011

See if the function below works for you. I haven't tested it thoroughly, so I would suggest you do so.

char *sstrstr(char *haystack, char *needle, size_t length)
{
    size_t needle_length = strlen(needle);
    size_t i;
    for (i = 0; i < length; i++) {
        if (i + needle_length > length) {
            return NULL;
        }
        if (strncmp(&haystack[i], needle, needle_length) == 0) {
            return &haystack[i];
        }
    }
    return NULL;
}