Open In App

strrchr() in C++

Last Updated : 04 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • str: specifies the pointer to the null-terminated string in which the search is to be performed.
  • chr: specifies the character to be searched.

Return Value:

  • The function returns a pointer to the last location of chr in the string if the chr is found.
  • If chr is not found, it returns a NULL pointer.

Example:

C++
// C++ program to demonstrate working strchr()
#include <cstring>
#include <iostream>
using namespace std;

int main()
{
    char str[] = "This is a string";
    char* ch = strrchr(str, 'i');
    cout << "Index of last occurrence of i: "
         << ch - str + 1;
    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:

C++
// 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
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.



Next Article
Article Tags :
Practice Tags :

Similar Reads