The function char *strrchr(const char *str, int c); searches for the last occurrence of character c(an unsigned char) in the string pointed by str.
Function prototype of strrchr
char *strrchr(const char *str, int c);
- str : This is the string to be scanned.
- c : Character to be searched.
Return value of strrchr
This function returns a pointer to the last occurrence of the character c in the string str. If character c is not found in str, it returns NULL.
C program using strrchr function
The following program shows the use of strrchr function to search last occurrence of a character in a string.
#include <stdio.h> #include <string.h> #include <conio.h> int main() { char string[100], ch; char *ptr; printf("Enter a string\n"); scanf("%s", string); printf("Enter a character to search\n"); scanf(" %c", &ch); ptr = strrchr(string, ch); if(NULL == ptr){ printf("'%c' not found", ch); } else { printf("Last Occurance of '%c' is at index %d\n", ch, ptr-string); } getch(); return(0); }
Output
Enter a string TechCrashCourse Enter a character to search C Last Occurance of 'C' is at index 9
Enter a string TechCrashCourse Enter a character to search C C not found