Skip to content
Related Articles

Related Articles

Improve Article

strrchr() function in C/C++

  • Difficulty Level : Basic
  • Last Updated : 27 Aug, 2018
Geek Week

The strrchr() function in C/C++ locates the last occurrence of a character in a string. It returns a pointer to the last occurrence in the string. The terminating null character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string. It is defined in cstring header file.
Syntax :

const char* strrchr( const char* str, int ch )
            or
char* strrchr( char* str, int ch )

Parameter :The function takes two mandatory parameters which are described below:

  • str : specifies the pointer to the null terminated string to be searched for.
  • ch: specifies the character to be search for.

Return Value: The function returns a pointer to the last location of ch in string, if the ch is found. If not found, it returns a null pointer.

Below programs illustrate the above function:

Program 1:






// C++ program to illustrate
// the strrchr() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Storing it in string array
    char string[] = "Geeks for Geeks";
  
    // The character we've to search for
    char character = 'k';
  
    // Storing in a pointer ptr
    char* ptr = strrchr(string, character);
  
    // ptr-string gives the index location
    if (ptr)
        cout << "Last position of " << character
             << " in " << string << " is " << ptr - string;
  
    // If the character we're searching is not present in the array
    else
        cout << character << " is not present "
             << string << endl;
    return 0;
}
Output:
Last position of k in Geeks for Geeks is 13

Program 2:




// C++ program to illustrate 
// the strrchr() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Storing it in string array
    char string[] = "Geeks for Geeks";
    char* ptr;
  
    // The character we've to search for
    char character = 'z';
  
    // Storing in a pointer ptr
    ptr = strrchr(string, character);
  
    // ptr-string gives the index location
    if (ptr)
        cout << "Last position of " << character
             << " in " << string << " is " << ptr - string;
  
    // If the character we're searching
    // is not present in the array
    else
        cout << character << " is not present in "
             << string << endl;
    return 0;
}
Output:
z is not present in Geeks for Geeks
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :