What is the strrchr() function in C++?
This function locates the last occurrence of a specified character in a string and returns a pointer to it. In this case, the termination of a null character is considered a part of the C-string. Following this, null character can be used to locate a pointer to the end of the string.
const char* strrchr( const char* str, int ch )//orchar* strrchr( char* str, int ch )
Parameters
str: This defines the pointer to the null, terminated string that is to be searched.ch: This defines the character to be searched.
Return value
- If the character is found the function returns a pointer to the last location of
ch. - If the character is not found the function returns a null pointer.
Code example
-
First, we declare the string and store the text in it.
-
Second, we define the character to be searched and then call the
strrchrfunction which searches the character in the string and returns the values to the pointer.
#include <bits/stdc++.h>using namespace std;int main(){char str[] = "Hello World. Welcome to Educative.";// The character to be searchedchar ch = 't';// Assigning a pointer to the store the return valuechar* ptr = strrchr(str, ch);// if the character is not foundif (!ptr)cout << ch << " is not present in ' "<< str << "'"<<endl;// If the character is foundedelsecout << "Last position of " << ch<< " in " << str << " is " << ptr - str;return 0;}