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++
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char denom[] = "Rs 10000000" ;
cout << "The original string is : " << denom;
char first = '1' ;
char * entire;
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.
Last Updated :
04 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...