Please review my strstr implementation. This is an interview question that say does not allow the use of strlen(). Is there a better way than using a boolean below?
#include <iostream>
#include <cstring>
char* my_strstr(char * s1, const char *s2)
{
if ( s1 == NULL || s2 == NULL )
return NULL;
size_t s2Size = 0;
const char *end = s2;
while (*end++)
++s2Size;
bool match;
while ( *s1 )
{
match = true;
for ( int i = 0; i < s2Size ; ++i )
{
if ( s1[i] != s2[i] )
{
match = false;
break;
}
}
if ( match )
return s1;
++s1;
}
return NULL;
}
const char* my_strstr(const char * s1, const char *s2)
{
return my_strstr(const_cast<char*>(s1),s2);
}
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 );
}