The strrchr() function searches the last occurrence of the specified character in the given string. This function works quite opposite to the function strchr() which searches the first occurrence of the character in the string.
C strrchr() function declaration
char *strrchr(const char *str, int ch)
str – The string in which the character ch is searched.
ch – The character that needs to be searched
Return value of strrchr()
It returns the pointer to the last occurrence of the character in the string. Which means if we display the return value of the strrchr() then it should display the part of the string starting from the last occurrence of the specified character.
Example: strrchr() function
#include <stdio.h> #include <string.h> int main () { const char str[] = "This-is-just-a-test-string"; const char ch = '-'; char *p, *p2; p = strrchr(str, ch); printf("String starting from last occurrence of %c is: %s\n", ch, p); p2 = strrchr(str, 'i'); printf("String starting from last occurrence of 'i' is: %s\n", p2); return 0; }
Output:
String starting from last occurrence of - is: -string String starting from last occurrence of 'i' is: ing
Leave a Reply