Jump to content

C Programming/string.h/strrchr

From Wikibooks, open books for an open world

strrchr is function in string.h.[1] It is mainly used to locate last occurrence of character in string, searching from the end. It returns a pointer to the last occurrence of character in the C string str. The terminating null-character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string.

Syntax

[edit | edit source]

In C, this function is declared as:

char *strrchr ( const char *, int );

str is a C string. character is the character to be located. It is passed as its int promotion, but it is internally converted back to char.

Return value

[edit | edit source]

A pointer to the last occurrence of character in str. If the value is not found, the function returns a null pointer.

Example

[edit | edit source]
#include <stdio.h>
#include <string.h>

int main(void)
{
    const char *str = "This is a sample string";
    char *pch = strrchr(str, 's');
    printf("Last occurrence of 's' found at %d\n", pch - str + 1);
    return 0;
}

Output : Last occurrence of 's' found at 18.

See also

[edit | edit source]

strchr

References

[edit | edit source]
  1. ISO/IEC 9899:1999 specification (PDF). p. 343, § 7.12.4.3.
[edit | edit source]