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.

Prototype

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

Parameter

This function has the following parameter.

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




Return

A pointer to the last occurrence of character in str.

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

Example


#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;
  pch=strrchr(str,'s');
  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.