Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function – strrchr()

C Library Function - strrchr()

C Standard Library - <string.h> C Standard Library -

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

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 - <string.h> C Standard Library -