strrchr

The strrchr function checks its argument for the occurrence of a given character. If the character is found, the function returns a pointer to the location where the character occurs. The return value is a NULL pointer if the character is not found in the string. The main objective of the function is similar to strchr, however, different from the strchr, strrchr looks for the last occurrence of the string of the character passed as argument.

The strrchr function has two parameters. The first parameter is a pointer to the null terminated string that is being searched. The second parameter is an integer that represents the character we are looking for.

The following code shows an example of strrchr in use:

#include        <string.h>
#include        <stdio.h>

int main()
{
        char *s = "abcfdfc";
        char *r1, *r2, *r3;
        r1 = strrchr(s, 'c');
        if (r1) printf("%s\n", r1);
        r2 = strrchr(s, 'f');
        if (r2) printf("%s\n", r2);
        r3 = strrchr(s, 'x');
        if (!r3) printf("char x was not found\n");
        return 0;
}

This code will print the following:

c
fc
char x was not found
Article created on 2008-08-19 22:19:48

Post a comment