C library functions -strrchr()

C Standard Library - <string.h>

Description

C Library Functionschar *strrchr(const char *str, int c)In the parameterstrSearches for the last occurrence of the character in the string pointed toc(an unsigned character) position.

Declaration

Below is the declaration of the strrchr() function.

char *strrchr(const char *str, int c)

Parameter

  • str-- C strings.
  • c-- The character to be searched for, usually passed as an integer (ASCII value), but it is ultimately converted back to char form.

Return Value

The strrchr() function searches forward from the end of the string until it finds the specified character or has searched the entire string. If the character is found, it returns a pointer to that character; otherwise, it returns NULL.

Example

The following example demonstrates the usage of the strrchr() function.

Example

#include <stdio.h> #include <string.h> int main () { int len; const char str[] = "https://www.example.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, this 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, this will produce the following result:

"Last 'o' found at position: 8"

'o' last appeared 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 - <string.h>

other extensions