Answer S14
/* Puzzle S14 Ends with */
#include <stdio.h>
#include <stdlib.h>
int endsWith( char const *bigString, char const *endString )
{
/* deal with special cases: empty strings */
if ( *endString == '\0' ) return 1;
if ( *bigString == '\0' ) return 0;
/* create two pointers that will run backwards through the strings */
char const *bs = bigString;
char const *es = endString;
/* find the last character of bigString */
while ( *bs ) bs++ ; bs-- ;
/* find the last character of endString */
while ( *es ) es++ ; es-- ;
/* check the two tails, working back to front */
while ( bs != bigString && es != endString && *bs == *es )
{
bs--; es--;
}
/* success, if first char of endString matches corresponding */
/* character of bigString */
return *bs == *es && es == endString ;
}
int main(int argc, char *argv[])
{
char *trials[][2] =
{
{"abcdef", "f"},
{"abcdef", "ef"},
{"abcdef", "def"},
{"abcdef", "cdef"},
{"abcdef", "abcdef"},
{"abcdef", "a"},
{"abcdef", "abc"},
{"abcdef", "xabcdef"},
{"abcdef", "xyzabcdef"},
{"abcdef", "rats"},
{"abbccddeef", "cc"},
{"abcdefg", "g"},
{"applecart", "cart"},
{"green", "apple"},
{"apple", ""},
{"", "rats"},
{"",""}
};
int j; char *loc;
for ( j=0; j<sizeof(trials)/sizeof(trials[0]); j++ )
{
int result = endsWith( trials[j][0], trials[j][1] ) ;
if ( result )
printf("%s\t ends with \t%s\n", trials[j][0], trials[j][1] );
else
printf("%s\t does not end with\t%s\n", trials[j][0], trials[j][1] );
}
return 0;
}