Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
function
communitycreator

What is the strrchr() function in C++?

Saad Akbar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 )
//or
char* 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 strrchr function 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 searched
char ch = 't';
// Assigning a pointer to the store the return value
char* ptr = strrchr(str, ch);
// if the character is not found
if (!ptr)
cout << ch << " is not present in ' "
<< str << "'"<<endl;
// If the character is founded
else
cout << "Last position of " << ch
<< " in " << str << " is " << ptr - str;
return 0;
}

RELATED TAGS

c++
function
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring