C++ Standard Library C++ STL Library

C++ <cstring> - strrchr() Function



The C++ <cstring> strrchr() function is used to find the last occurrence of character in the byte string pointed to by str. The terminating null character is considered as a part of the string and can be found if searching for '\0'.

The function returns pointer to the last occurrence of character in str, or null pointer if character is not found in str.

Syntax

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

Parameters

str Specify pointer to the null-terminated byte string to be searched in.
character Specify the character to searched for.

Return Value

Returns pointer to the last occurrence of character in str, or null pointer if character is not found in str.

Example:

The example below shows the usage of strrchr() function.

#include <iostream>
#include <cstring>
using namespace std;
 
int main (){
  char MyStr[100] = "To be, or not to be, that is the question.";
  char * search;
  
  //searching for last occurrences of 'o' in MyStr
  search = strrchr(MyStr, 'o');

  //displaying the result
  if(search != NULL)
    cout<<"Found at: "<<(search-MyStr+1);
  else
    cout<<"Not Found.\n";
 
  return 0;
}

The output of the above code will be:

Found at: 40

❮ C++ <cstring> Library