Jun 24, 2016

C Programming #74: strlen implementation

C Programming #74: strlen implementation

Following article implements our own version of strlen implementation. Please review article strings and string.h library if not already done. Since our implementation function name would clash with standard implementation, lets prefix my_ to it. We know the prototype of my_strlen is as follow.

/*Return the length of the string s.*/
size_t my_strlen(const char *s);

We need to have a counter that would go though the string till it hits '\0;.

#include <stdio.h>
#include <string.h>
size_t my_strlen(const char *s);
int main()
{
   char a[50] = "Hello world";
   printf("strlen of %s is %d\n", a, strlen(a));
   printf("my_strlen of %s is %d\n", a, my_strlen(a));
}
size_t my_strlen(const char *s)
{
   size_t len = 0;
   while(*s++ != '\0')
      len++;
   return len;
}
strlen of Hello world is 11
my_strlen of Hello world is 11

Now with iteration we are actually increment s as well as len, this could be avoided by implementing it as follows.

size_t my_strlen(const char *s)
{
   char *p = s;
   while(*p++ != '\0');
   return (p - s - 1);
}

Note that above implementation would not be efficient and is not doing error checking. Actual implementation strlen is done in glibc implementation. glibc would have done all sorts of optimization depending on artitection 32 bit vs 64 bit. so on.

No comments :

Post a Comment