I'd write a function that returns the length of the common suffix, zero if none:
Code:
size_t common_suffix(const char *const string1, const char *const string2)
{
const size_t length1 = (string1 != NULL) ? strlen(string1) : 0;
const size_t length2 = (string2 != NULL) ? strlen(string2) : 0;
const size_t n = (length1 < length2) ? length1 : length2;
size_t i = 1; /* Offset before end of string, 1 .. n, inclusive. */
/* As long as the i'th characters from the end match, increase i. */
while (i <= n && string1[length1 - i] == string2[length2 - i])
i++;
/* The length of the common suffix is i - 1 characters. */
return i - 1;
}
I used the ternary operator condition ? value-if-true : value-if-false to treat NULL pointers as if they were empty strings, and to save the smaller of the two string lengths into n.
The index i is always between 1 and shorter string length, inclusive, so you can use string[ length - i ] to access the i'th character from the end of the string.
Using your example strings, you can get the common suffix and its length using
Code:
static const char *const one = "destination";
static const char *const two = "procrastination";
size_t common;
common = common_suffix(one, two);
if (common > 0)
printf("'%s' and '%s' have a %d-character common suffix, '%s'.\n", one, two, (int)common, one + common);
else
printf("'%s' and '%s' do not have a common suffix.\n", one, two);