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.
Links
- Next Article - C Programming #79: strstr implementation
- Previous Article - C Programming #77: strcmp implementation
- All Article - C Programming
In my_strchr function 2 nd arguement is "const char c" not "int c" .
ReplyDeletePlease correct it.
Thanks for correction. I have rectified the implementation.
Delete