Open In App

strrchr() in C++

C++ strrchr() function finds the location of the last occurrence of the specified character in the given string and returns the pointer to it. It returns the NULL pointer if the character is not found.

It is a standard library function of C which is inherited by C++ so it only works on C-style strings (i.e. array of characters). It is defined inside <cstring> and <string.h> header files.

Syntax:

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

Parameter:

Return Value:

Example:




// C++ code to demonstrate the application of
// strrchr()
#include <cstring>
#include <iostream>
using namespace std;
 
int main()
{
 
    // initializing the denomination
    char denom[] = "Rs 10000000";
 
    // Printing original string
    cout << "The original string is : " << denom;
 
    // initializing the initial number
    char first = '1';
    char* entire;
 
    // Use of strrchr()
    // returns entire number
    entire = strrchr(denom, first);
 
    cout << "\nThe denomination value is : " << entire;
 
    return 0;
}

Output
Index of last occurrence of i: 14

Time Complexity: O(n),

Space Complexity: O(1),

where n is the length of the string.

Practical Application of strrchr() function in C++

Since it returns the entire string after the last occurrence of a particular character, it can be used to extract the suffix of a string. For e.g to know the entire leading zeroes in a denomination when we know the first number. 

Example:





Output
The original string is : Rs 10000000
The denomination value is : 10000000

Time Complexity: O(N), as time complexity for function strrhcr() is O(N) where N is the length of given String .

Auxiliary Space: O(1),  since we are not using any extra space.


Article Tags :
C++