Mark Bluemel
6/23/2011 1:08:00 PM
On 06/23/2011 11:56 AM, arnuld wrote:
> K&r2, exercise 5-4, page 107
>
> Write the functions strend(s,t), which returns 1 if the string t occurs
> at the end of the string s, and zero otherwise.
Your solution presupposes strlen(), so it may as well presuppose
strcmp(). If you don't already have them, write them as building blocks
for this...
As others have suggested one testcase doesn't prove much - even a
stopped clock is right twice a day.
Here's something I threw together.
#include <stdio.h>
#include <string.h>
int strend(const char* s1, const char* s2);
int main(void)
{
const char* arr1[] = { NULL,
"",
"comp.lang.c",
"comp.lang.perl",
"uk.fan.monkees"};
const char* arr2[] = { NULL,
"",
"comp.lang.",
"unutterablyLongString",
"lang.c",
"ees",
"l"
};
int i;
int j;
for (i = 0 ; i < (sizeof arr1/sizeof (char *)); i++) {
for (j = 0 ; j < (sizeof arr2/sizeof (char *)); j++) {
printf("strend(%s, %s) = %d\n", arr1[i], arr2[j], strend(arr1[i],
arr2[j]));
}
}
return 0;
}
/* return 1 if str2 occurs at the end of str1, zero otherwise */
int strend(const char* str1, const char* str2)
{
int str1_len;
int str2_len;
const char *comparison_start;
if ((str1 == NULL) || (str2 == NULL)) {
return 0;
}
str1_len = strlen(str1);
str2_len = strlen(str2);
if (str2_len == 0) {
return 0;
}
if (str2_len > str1_len) {
return 0;
}
comparison_start = str1 + str1_len - str2_len;
return !strcmp(comparison_start,str2);
}