[H-8]
Write function that finds the first occurance
of a substring in another (usually larger) source string. If the substring is
found, a pointer to the beginning of the first occurance in the source string
is returned. If the substring is not found, NULL is returned. Here is a testing
program:
/* Puzzle S15 -- Find Substring */ #include <stdio.h> #include <stdlib.h> int startsWith( char const *bigString, char const *start ) { } char *findSubstring( char const *source, char const *sub ) { } int main(int argc, char *argv[]) { char *trials[][2] = { {"abcdef", "a"}, {"abcdef", "abc"}, {"abcdef", "d"}, {"abcdef", "def"}, {"abcdef", "f"}, {"abcdef", "xyz"}, {"abcdef", "axx"}, {"abcdef", "abcdefg"}, {"abcdef", "rats"}, {"abbccddeef", "cc"}, {"abcdefg", "g"}, {"applecart", "c"}, {"green", "apple"}, {"apple", ""}, {"", "rats"}, {"",""} }; int j; char *loc; for ( j=0; j<sizeof(trials)/sizeof(trials[0]); j++ ) { loc = findSubstring( trials[j][0], trials[j][1] ); if ( loc ) printf("%s : %s : %s\n", trials[j][0], trials[j][1], loc ); else printf("%s : %s : %s\n", trials[j][0], trials[j][1], "not found" ); } return 0;
It will be useful to write this function using your startsWith()
function.
Note: this function is similar to the standard function strstr()
.