Table of Contents

    strrchr() Function in C: Finding Last Occurrence of Character in String

    strrchr() Function in C: Finding Last Occurrence of Character in String

    strrchr() function in C returns pointer to the last occurrence of the character in a given string. Syntax for strrchr( ) function is given below.

    Syntax

    char *strrchr(const char *str, int ch);

    Returns

    The strrchr() function returns a pointer to the last occurrence of the low-order byte of ch in the string pointed to by str. If no match is found, a null pointer is returned.

    Program 1

    #include 
    #include 
    int main(void)
    {
    char *p;
    p = strrchr("this is a test", 'i');
    printf(p);
    return 0;
    }

    Output

    is a test

    Program 2

    In this program, strrchr( ) function is used to locate last occurrence of the character 'i' in the string "This is a string for testing". Last occurrence of character 'i' is located at position 26 and pointer is returned at last occurrence of the character 'i'.

    #include 
    #include 
    int main ()
    {
      char string[55] ="This is a string for testing";
      char *p;
      p = strrchr (string,'i');
     
      printf ("Character i is found at position %d\n",p-string+1);
      printf ("Last occurrence of character \"i\" in \"%s\" is" \
               " \"%s\"",string, p);
     
       return 0;
    }

    Output

    Character i is found at position 26
    Last occurrence of character "i" in "This is a string for testing" is "ing"