strstr implementation from scratch

mvmalderen 0 Tallied Votes 567 Views Share

This is how I would write the standard library function strstr if I had to implement it from scratch.

#include <iostream>

const char *mystrstr(const char *p, const char *q);

int main()
{
    char t1[256] = {0};
    char t2[256] = {0};

    std::cout << "Enter a string: ";
    std::cin.getline(t1, 256);

    std::cout << "Search for: ";
    std::cin.getline(t2, 256);

    if( const char *p = mystrstr(t1, t2) )
        std::cout << "Found: " << p << std::endl;
    else
        std::cout << "Not found!" << std::endl;

    return 0;
}

const char *mystrstr(const char *p, const char *q)
{
    for( ; *p; ++p)
    {
        const char *p_tmp = p;
        const char *q_tmp = q;

        for( ; *p_tmp == *q_tmp && *q_tmp; ++p_tmp, ++q_tmp);
        if( !*q_tmp ) return p;
    }
    return 0;
}
/* Sample run:

Enter a string: Hello World
Search for: Wo
Found: World

Enter a string: Hi Daniweb!
Search for: Hill
Not found!
*/
mvmalderen 2,072 Postaholic

Bug Fix!
To begin: the mystrstr function takes two pointers as its arguments, one to the string where it has to search in, and one to the substring where it has to search for.
But what if the substring is: "" ?
In that case the function won't return a null-pointer, instead it will return the same pointer as it received as its first argument.

So, how to fix this nasty bug?
Change this if: if( !*q_tmp ) to if( *p == *q && !*q_tmp ) :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.