[H-11]
Write a function that determines if one
string ends with all the characters of another. For example, "applecart"
ends with "cart", but "applecart" does not end with "bart".
Every string ends with the null string. Here is a testing program:
/* Puzzle S14 -- ends with */ #include <stdio.h> #include <stdlib.h> int endsWith( char const *bigString, char const *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; 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; }
Note: This function is much harder to write than startsWith()
.
One difficulty is that the comparison is made starting at the end of both strings
and working forward, but there is no null byte at the beginning of the strings
that say where they start.