C++ strrchr()

The strrchr() function in C++ searches for the last occurrence of a character in a string.

strrchr() prototype

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

The strrchr() function takes two arguments: str and ch. It searches for the last occurrence of the character ch in the string pointed to by str.

It is defined in <cstring> header file.

strrchr() Parameters

  • ptr: Pointer to the null terminated string to be searched for.
  • ch: Character to search for.

strrchr() Return value

If ch is found, the strrchr() function returns a pointer to the last location of ch in str, otherwise returns a null pointer.

Example: How strrchr() function works

#include <cstring>
#include <iostream>

using namespace std;

int main()
    char str[] = "Hello World!";
    char ch = 'o';
    char *p = strrchr(str, ch);
    if (p)
        cout << "Last position of " << ch << " in \"" << str << "\" is " << p-str;
        cout << ch << " is not present \"" << str << "\"";

    return 0;

When you run the program, the output will be:

Last position of o in "Hello World!" is 7
Did you find this article helpful?