If the haystack is a few Gb, why traverse it simply to determine the upper bound? Traverse the haystack only once (or less)...
Little challenges are a good chance to play with code:
#include <stdio.h>
int str_find( char* needle, char* haystack) {
size_t i = 0, matched = 0;
while( haystack[ i ] && needle[matched] )
if( needle[ matched ] == haystack[i] )
matched++, i++;
else if( matched )
i -= matched - 1, matched = 0; // rewind a bit and try again
else i++;
return needle[matched] == '\0' ? i - matched : -1;
}
int main() {
char *hay = "longlongagoinagalaxyfarfarawaygeorgelucasmadeababananana";
char *needles[] = { "far", "lucas", "yoda", "force", "banana" };
for( int i = 0; i < sizeof needles/sizeof needles[0]; i++ )
printf( "%s - %sfound\n", needles[i], str_find( needles[i], hay ) < 0 ? "not " : "" );
return 0;
}
Output
far - found
lucas - found
yoda - not found
force - not found
banana - found
EDIT:
In fact, rather than simply found/not-found, this challenge suggests finding multiple instances of any needle (or not finding any) so is worthy of more development.
Here, the return from str_find() is put to more use and the testing done by main() made a bit more elaborate.
This code does not prevent searching for a zero length needle. If someone can describe what a zero-length needle looks like, I would appreciate reading about it in the comments.
#include <stdio.h>
char *str_find( char *needle, char *haystack ) {
size_t i = 0, matched = 0;
while( needle[ matched ] && haystack[ i ] )
if( needle[ matched ] == haystack[i] )
matched++, i++;
else if( matched )
i -= matched - 1, matched = 0; // rewind a bit and try again
else i++;
return needle[ matched ] ? NULL : haystack + i - matched;
}
int main() {
char *hay = "longlongagoinagalaxyfarfarawaygeorgelucasmadeababananana";
char *needles[] = { "long", "far", "lucas", "yoda", "force", "banana", "nananana" };
for( size_t i = 0; i < sizeof needles/sizeof needles[0]; i++ ) {
printf( "%s:\n", needles[i] );
size_t count = 0;
for( char *p = hay; ( p = str_find( needles[i], p ) ) != NULL; p++ )
printf( "\t#%d '%-.10s'\n", ++count, p );
printf( "%d instances\n", count );
}
return 0;
}
Output showing the 'needle' and a few more characters of "context" following the needle.
long:
#1 'longlongag'
#2 'longagoina'
2 instances
far:
#1 'farfaraway'
#2 'farawaygeo'
2 instances
lucas:
#1 'lucasmadea'
1 instances
yoda:
0 instances
force:
0 instances
banana:
#1 'bananana'
1 instances
nananana:
0 instances