Jun 28, 2016

C Programming #78: strchr implementation

C Programming #78: strchr implementation

Following article implements our own version of strchr 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_strchr is as follow.

/*Return a pointer to the first occurrence 
of the character c in the string s.*/
char *my_strchr(const char *s, int c);


From the comment above my_strchr we need to traverse the array till we hit character, in that case we need to return the pointer to that occurrence or if the string is not found return NULL.

#include <stdio.h>
char *my_strchr(const char *s, const char c);
int main()
{
   char a[50] = "Hello world";

   printf("Search w result is %s\n", my_strchr(a, 'w'));
   printf("Search z result is %s\n", my_strchr(a, 'z'));

   return 0;
}
char *my_strchr(const char *s, const char c)
{
   while(*s != c && *s != '\0') {
      s++;
   }
   if(*s == c) {
      return s;
   }else {
      return NULL;
   }
}
Search w result is world
Search z result is (null)

Hope that clarifies the implementation. Never use custom implementation like this, always use the standard implementation provided in glibc.

2 comments :

  1. In my_strchr function 2 nd arguement is "const char c" not "int c" .
    Please correct it.

    ReplyDelete
    Replies
    1. Thanks for correction. I have rectified the implementation.

      Delete