What about:
char *strnstr(char *haystack, char *needle, size_t len) { if (len == 0) return haystack; while (haystack = strchr(haystack, needle[0])) { if (!strncmp(haystack, needle, len)) return haystack; haystack++; } return 0; }
If you want haystack not complete to zero, you will need two length arguments:
char *memmem(char *haystack, size_t hlen, char *needle, size_t nlen) { if (nlen == 0) return haystack; if (hlen < nlen) return 0; char *hlimit = haystack + hlen - nlen + 1; while (haystack = memchr(haystack, needle[0], hlimit-haystack)) { if (!memcmp(haystack, needle, nlen)) return haystack; haystack++; } return 0; }
which is available in GNU libc, although older versions do not work.
Chris dodd
source share