What is the strrchr() function in C++?

This function locates the last occurrence of a specified character in a string and returns a pointer to it. In this case, the termination of a null character is considered a part of the C-string. Following this, null character can be used to locate a pointer to the end of the string.

const char* strrchr( const char* str, int ch )
//or
char* strrchr( char* str, int ch )

Parameters

  • str: This defines the pointer to the null, terminated string that is to be searched.
  • ch: This defines the character to be searched.

Return value

  • If the character is found the function returns a pointer to the last location of ch.
  • If the character is not found the function returns a null pointer.

Code example

  • First, we declare the string and store the text in it.

  • Second, we define the character to be searched and then call the strrchr function which searches the character in the string and returns the values to the pointer.

#include <bits/stdc++.h>
using namespace std;
int main()
{
char str[] = "Hello World. Welcome to Educative.";
// The character to be searched
char ch = 't';
// Assigning a pointer to the store the return value
char* ptr = strrchr(str, ch);
// if the character is not found
if (!ptr)
cout << ch << " is not present in ' "
<< str << "'"<<endl;
// If the character is founded
else
cout << "Last position of " << ch
<< " in " << str << " is " << ptr - str;
return 0;
}

Free Resources