Jobe, my very first reaction would be, why not write a generic function instead of restricting yourself with search strings of length 2 or 3.
goes out of bound. Isn't that bad coding?
Its not bad coding, its
wrong coding. How can you expect your program to perform properly and in the right manner if you are basing your programming logic on computations on areas of memory which don't belong to you ?
Also the trick which you use will soon turn out to be cumbersome if you are asked to do the same with 3 letters, 4 letters, n letters etc.
My thoughts: always look for generic patterns in the problem statement and if they don't incur additional overheads for that case, go ahead and implement them.
For eg here is one implementation which is possible. I haven't tried it but it should pretty much work.
// retuns the last position in the string where the match was found
// modifies the count parameter passed by reference which displays the
// number of times substring occurs.
int my_strstr( const char* str1, const char* str2, int* count )
{
int i = 0 ;
int len1 = strlen( str1 ) ;
int len2 = strlen( str2 ) ;
int pos = 0 ;
*count = 0 ; // initialize the counter
for( i = 0; i < len1; ++i )
{
if( strncmp( ( str1 + i ), str2, len2 ) == 0 )
{
(*count)++ ;
pos = i ;
}
}
return pos ;
}
int main( void )
{
int count ;
char str[] = "ababababa" ;
char search_str[] = "ab" ;
int match = my_strstr( str, search_str, &count ) ;
printf( "The last occurance of \'%s\' was found in \'%s\' at %d.",
str, search_str, match ) ;
printf( "\nThe count of \'%s\' is %d.", search_str, count ) ;
getchar( ) ;
return 0 ;
}
You can change the function so that you get it to return the char pointer rather than returning position or you can make the function do both by keeping its prototype as:
char* my_strstr( const char* str1, const char* str2, int* count, int* pos )
which makes the function return char pointer to the substring found as well as modifies the parameters passed to it to reflect the count of substring as well as the position of the last substring.
Hope it helped, bye.