C Function Strrchr
# C Library Function - strrchr()
[ C Standard Library - ](#)
## Description
The C library function **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**.
## Declaration
Below is the declaration for the strrchr() function.
char *strrchr(const char *str, int c)
## Parameters
* **str** -- C string.
* **c** -- The character to be searched. It is passed as an int, but the function performs a character comparison using the value of the character converted to an unsigned char.
## Return Value
The strrchr() function searches from the end of the string towards the beginning until the specified character is found or the entire string has been searched. If the character is found, it returns a pointer to the character; otherwise, it returns NULL.
## Example
The following example demonstrates the usage of the strrchr() function.
## Example
#include#includeint main(){int len; const char str[] = ""; const char ch = '.'; char *ret; ret = strrchr(str, ch); printf("|%c| The string after is - |%s|n", ch, ret); return(0); }
Let us compile and run the above program, this will produce the following result:
|.| The string after is - |.com|
The following example uses the strrchr() function to find the character 'o' in the string "Hello, World!" and returns the position of the last 'o':
## Example
#include#includeint main(){const char *str = "Hello, World!"; char ch = 'o'; char *lastO = strrchr(str, ch); if(lastO != NULL){printf("Last '%c' found at position: %ldn", ch, lastO - str); }else{printf("'%c' not found in the string.n", ch); }return 0; }
Let us compile and run the above program, this will produce the following result:
"Last 'o' found at position: 8"
The last occurrence of 'o' is at position 8. If the character 'o' is not found in the string, it will display "'o' not found in the string.".
[ C Standard Library - ](#)
YouTip