Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

strrchr — last occurrence of a character

strrchr from <string.h> returns a pointer to the last occurrence of a character in a string, or NULL. The search includes the terminating '\0'.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <string.h>
QChar *strrchr(QChar *s, int c);

strrchr(s, c) finds the last occurrence of c after conversion to char, unlike strchr, which finds the first. It returns a pointer into the original string or NULL; it makes no copy. For c == '\0', it points to the terminator.

In the C23 notation, QChar is a standard placeholder, not a type to declare: a char * argument produces char *, and const char * produces const char *. s must point to an accessible null-terminated string; NULL or no accessible terminator causes undefined behavior. Check the result before dereferencing or pointer arithmetic. Do not modify a string literal through the returned pointer.

Examples

#include <stdio.h>
#include <string.h>

int main(void)
{
    const char text[] = "a/b/c";
    const char *last = strrchr(text, '/');
    const char *end = strrchr(text, '\0');

    if (last != NULL) {
        printf("suffix: %s\n", last + 1);
    }
    printf("length: %td\n", end - text);
    printf("missing: %s\n", strrchr(text, '?') == NULL ? "yes" : "no");
    return 0;
}

Result

suffix: c
length: 5
missing: yes

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources