C String Functions - C strrchr

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

Searches for the last occurrence of the character c (an unsigned char) in the string pointed to by the argument str.

The terminating null character is considered to be part of the string.

Returns a pointer pointing to the last matching character, or null if no match was found.


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


This function has the following parameter.

C string.
Character to be located. It is passed as its int promotion, but it is internally converted back to char.


A pointer to the last occurrence of character in str.

If the character is not found, the function returns a null pointer.


#include <stdio.h>
#include <string.h>
/*from  w w  w .  jav a 2 s  .co m*/
int main (){
  char str[] = "This is a sample string";
  char * pch;
  printf ("Last occurence of 's' found at %d \n",pch-str+1);
  return 0;

The code above generates the following result.

Example 2

#include <string.h>
#include <stdio.h>
int main(void){
    char szSomeFileName[] = "c:/foo/bar/foobar.txt";
    char *pLastSlash = strrchr(szSomeFileName, '/');
    char *pszBaseName = pLastSlash ? pLastSlash + 1 : szSomeFileName;
    printf("Base Name: %s", pszBaseName);

The code above generates the following result.