4 of 5
Bounds fix
200_success
  • 143.4k
  • 22
  • 186
  • 470

By counting the length of s2, you missed the point of this exercise. Technically, you didn't call strlen(), but you emulated it, which is arguably even worse. The point was to test your proficiency with pointers, and you failed this interview question. (Why not count the length? Because it's possible to do it without incurring the cost of that O(n) operation. The only time you need to walk along the entire length of s2 is when a match is imminent.)

The strstr(3) documentation probably calls the arguments s1 and s2. However, I'll borrow a rare piece of wisdom from the PHP documentation and call the arguments haystack and needle.

Don't use variables to control the execution flow. Prefer to use more active means such as continue, break, and return. If you have detected a match, what are you waiting for? Celebrate your success with an immediate return!

Your imports are wrong. The only library function you call is printf(), so you should #include <cstdio>.

Here's a solution.

#include <cstdio>

char* my_strstr(char *haystack, const char *needle) {
    if (haystack == NULL || needle == NULL) {
        return NULL;
    }

    for ( ; *haystack; haystack++) {
        // Is the needle at this point in the haystack?
        const char *h, *n;
        for (h = haystack, n = needle; *h && (*h == *n); ++h, ++n) {
            // Match is progressing
        }
        if (*n == '\0') {
            // Found match!
            return haystack;
        }
        // Didn't match here.  Try again further along haystack.
    }
    return NULL;
}

const char* my_strstr(const char *haystack, const char *needle) {
    return my_strstr(const_cast<char *>(haystack), needle);
}

int main() {
    const char *str = "This is a strstr test";
    const char *search = "strstr";

    const char *result = my_strstr(str, search);

    if (result)
        printf("original: %s\n item: %s\n found: %s\n", str, search, result);
    return 0;
}
200_success
  • 143.4k
  • 22
  • 186
  • 470