C Library Function - strrchr()
Description
C library function **char strrchr(const char str, int c) Searches the first str searches for the last occurrence of the character in the string pointed to by cand returns its position.
Declaration
Below is the declaration of the strrchr() function.
char *strrchr(const char *str, int c)
Parameters
- str -- C string.
- c -- the character to search for, usually passed as an integer (ASCII value), but eventually converted back to char form.
Return Value
The strrchr() function searches forward from the end of the string until the specified character is found or the whole string has been searched. If the character is found, it returns a pointer to that character; otherwise, it returns NULL.
Example
The following example demonstrates the use of the strrchr() function.
Example
#include
<
stdio.h
#include
<
string.h
int
main
(
)
{
int
len;
const
char
str
[
]
=
"
https://www.runoob.com
"
;
const
char
ch
= '.';
char
ret
;
ret
=
strrchr
(
str
,
ch
)
;
printf
(
"
The string after |%c| is - |%s|
\
n
"
,
ch
,
ret
)
;
return
(
0
)
;
}
Let's compile and run the above program, which will produce the following result:
|.| 之后的字符串是 - |.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
<
stdio.h
#include
<
string.h
int
main
(
)
{
const
char
str
=
"Hello, World!
"
;
char
ch
= '
o
';
char
lastO
=
strrchr
(
str
,
ch
)
;
if
(
lastO
!=
NULL
)
{
printf
(
"
Last '%c' found at position: %ld
\
n
"
,
ch
,
lastO
str
)
;
}
else
{
printf
(
"
'%c' not found in the string.
\
n
"
,
ch
)
;
}
return
0
;
}
Let's compile and run the above program, which will produce the following result:
"Last 'o' found at position: 8"
'o' last appears at position 8. If the character 'o' is not found in the string, "'o' not found in the string." will be displayed.
C Standard Library -