C string library function strrchr( )


In this article, you will learn about C string library function strrchr( ) with step by step explanation and proper example.

c string library function strrchr( )

strrchr( ) is string manipulation function of C programming that is used for a search operation in the string. This function is defined under string header file string.h.

#include<string.h>

Function prototype of C string library function strrchr( )

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

where,

                 str = string that needs to be scanned

                 ch = character that needs to be searched in str

This standard library function searches for the character ch in the string str and locates its last occurrence. If the character is found, a pointer to that character is returned else a NULL pointer is returned.

How strrchr( ) function works?

working c strrchr

Let’s be more clear from the following example.

Example: C program to illustrate the use of C string library function strrchr( )

/*Use of string library function strrchr( )*/

#include<stdio.h>
#include<string.h>

int main()
{
   //initialize char pointer str
   const char *str = "Learn c from trytoprogram.com";

   int ch = 'c'; //character for searching in str

   printf("str = %s\n\n", str);
   printf("searching character ch = %c\n\n", ch);

   printf("Last occurrence of '%c' in str is = %s\n", ch, strrchr( str, ch));

   return 0;
}

Output

c strrchr output

Explanation

As we mentioned above, strrchr( ) function in this program search for the character 'c' in the string "Learc c from trytoprogram.com".

This program detects the last occurrence of the character 'c'  in str. Therefore it displays com as output.