Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

strrchr() in C++

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

9

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.

This article is contributed by Ayush Saxena and Vaishnavi Tripathi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Last Updated : 24 Apr, 2023
Like Article
Save Article