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

Writing the function strend()

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

Problem

Due to being unable to ask a C programming language expert or advanced user in person, I'm posting this simple question about my C code. Today I was refreshing my C with exercise 5.4 of the C programming Language 2nd Edition by K&R, which is a very simple exercise:

Do you think that my way of handling pointers is 'very good' or 'world class'?

I know the example is short/simple but that question comes to my mind because I want to know the opinion from other knowledgeable people about the subject, if you want to critique my code please do so. I'm always trying to push my current C knowledge to the next level.

/*----------------------------------------------------*/
#include 
#include 
#include 
/*
  Exercise 5-4.
  Write the function strend(s,t) 
  which returns 1 if the string t occurs at the
  end of the string s, and zero otherwise.
*/
int strend(char *s, char *t);

int main(int argc, char *argv[])
{
  int rt; 

  if ( rt = strend("Unix Powered", "red"))
     printf("occurs\n");

 return EXIT_SUCCESS;
}

/*
  find if 't' occurs at the end of 's'
*/
int
strend(char *s, char *t)
{
   while (*s)
      s++;
   if ( strlen(s) < strlen(t))
      return 0;
   s -= strlen(t);
   for (; *t ; s++, t++) {
      if ( *s != *t) 
         return 0;
   }
 return 1;
} 
/*----------------------------------------------------*/

Solution

I would write the function like this:

#include 

/* Return 1 if string s1 ends with s2; return 0 otherwise. */
int strend(const char *s1, const char *s2)
{
    size_t l1 = strlen(s1);
    size_t l2 = strlen(s2);
    return l2 <= l1 && memcmp(s2, s1 + l1 - l2, l2) == 0;
}


If we know the length of the strings (as here), then memcmp is usually the quickest way to compare them. That's because memcmp doesn't have to check for the end of the string (unlike strcmp), and because standard library implementations of memcmp tend to be well optimized, using word-at-a-time comparison and other tricks if possible.

Code Snippets

#include <string.h>

/* Return 1 if string s1 ends with s2; return 0 otherwise. */
int strend(const char *s1, const char *s2)
{
    size_t l1 = strlen(s1);
    size_t l2 = strlen(s2);
    return l2 <= l1 && memcmp(s2, s1 + l1 - l2, l2) == 0;
}

Context

StackExchange Code Review Q#84764, answer score: 7

Revisions (0)

No revisions yet.