strstr implementation from scratch

tux4life 0 Tallied Votes 198 Views Share

Hi, please don't blame me for reinventing the wheel, I was bored and had nothing to do, so I thought: what would I write?
And apparently this code is the result :P

/**
@author: Mathias Van Malderen (tux4life)
*/
const char *astrstr(const char *s1, const char *s2)
{
    for(; *s1; s1++)
    {
        for(int i=0; *s1 && *s2; s1++, s2++, i++)
        {
            if(!(*s1==*s2))
            {
                s1-=i;
                s2-=i;
                break;
            } else if(!(*(s2+1))) {
                return s1-i;
	    }
        }
    }
    return 0;
}
tux4life 2,072 Postaholic

BTW, You can quickly adapt this code to C by just declaring i at the top of astrstr :)

Forgot to mention: The function behaves exactly as the normal strstr (so actually there was no need for a function like astrstr :P):
When the substring is found it returns a pointer to the beginning of that substring, otherwise, when the string you're searching for isn't found, it will return a NULL-pointer :)

You can change it return type from const char* to char* if there's need to, or you can overload the function.

IUnknown 0 Newbie Poster

You don't check whether s1 and\ or s2 are NULL pointers. If one of them is NULL, you'll get access violation \ segmentation fault exception.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

tux4life said his version worked exactly like the original -- and core dump or seg violation is what the original does too :)

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.