Write a function
strend(s, t)
which returns1
if the stringt
occurs at the end ofs
, and0
otherwise.
Here is my solution:
unsigned int strend(char *source, char *pattern) {
char *saver = pattern;
while(*source)
source++;
while(*saver)
saver++;
while(saver >= pattern)
if(*saver-- != *source--)
return 0;
return 1;
}
There are 2 while
loops that will run until source
and saver
will point to the end of the string that they are representing. You will notice the presence of the variable saver
, at the end of the second while loop this variable will have the value pattern + X
, where X
represent the number of charachters in the string pattern
.
By using the variable saver
I know when to stop the third loop. When saver
is less than pattern
that means that every charachter in the string pattern
was compared with the coresponding one in source
. At each iteration of the loop I check if the current charachter that saver
points to is equal to the coresponding charachter in source
.
Here is my second version:
unsigned int strend(char *source, char *pattern) {
char *saver = pattern + strlen(pattern);
source += strlen(source);
while(saver >= pattern)
if(*source-- != *saver--)
return 0;
return 1;
}
There is a dependency between my second implementation of strend
and strlen
. I, also, have some problems with the naming of the variable saver
. What would be a more suggestive name for its purpose?
The exercise can be found at page 121 in K&R second edition.
strlen
in your second example is generally a good thing. Its reuse of existing functionality lets you focus on new problems, rather than ones that are already solved. (But it's good to know how to roll your own, too!) \$\endgroup\$char*
toconst char*
\$\endgroup\$