HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

strend, function that checks the occurence of a pattern at the end of a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theoccurencechecksfunctionstrendthatendstringpattern

Problem

Write a function strend(s, t) which returns 1 if the string t occurs at the end of s, and 0 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.

Solution

I see no point in avoiding the use of Standard Library functions. Learning to
use them is part of becoming a proficient C programmer. Hence using strlen
is good and reinventing strcmp or memcmp, as you have done, is bad. Making the return
value unsigned is just extra typing/noise and achieves nothing. Here is a
simplified version:

int strend1(const char *str, const char *pattern)
{
    size_t plen = strlen(pattern);
    size_t slen = strlen(str);
    return (plen <= slen) 
           && !memcmp(pattern, str + slen - plen, plen) ? 1 : 0;
}


Note that the parameters are const.

Code Snippets

int strend1(const char *str, const char *pattern)
{
    size_t plen = strlen(pattern);
    size_t slen = strlen(str);
    return (plen <= slen) 
           && !memcmp(pattern, str + slen - plen, plen) ? 1 : 0;
}

Context

StackExchange Code Review Q#40664, answer score: 10

Revisions (0)

No revisions yet.