Search code examples
cstrrchr

How can I write actual strrchr function in C language?


Description Searches for the last occurrence of the character c (an unsigned char) in the string pointed to by the argument str. The terminating null character is considered to be part of the string. Returns a pointer pointing to the last matching character, or null if no match was found.

Image with examples


Solution

  • The function strrchr() is very simple to write in C: it suffices to iterate on the string, remembering the last position where the character was seen...

    #include <string.h>
    
    /* 7.24.5.5 The strrchr function */
    char *strrchr(const char *s, int c) {
        const char *p = NULL;
    
        for (;;) {
            if (*s == (char)c)
                p = s;
            if (*s++ == '\0')
                return (char *)p;
        }
    }