strrchr() in C: Find the Last Character Match

strrchr() is a standard C function that returns a pointer to the last occurrence of a character in a null-terminated string. If the character is not found, it returns NULL.

Syntax Top ↑

char *strrchr(const char *str, int ch);

Find the Last Character Match Top ↑

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

int main(void) {
    const char text[] = "Welcome to plus2net";
    const char *pos = strrchr(text, 'e');

    if (pos != NULL) {
        printf("Zero-based index: %td\n", pos - text);
        printf("From match: %s\n", pos);
    } else {
        printf("Character not found.\n");
    }

    return 0;
}

Output

Zero-based index: 17\nFrom match: et

Subtracting the start pointer from the returned pointer gives a zero-based index. Always check for NULL before subtracting or dereferencing the result.

Find the File Name After the Last Slash Top ↑

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

int main(void) {
    const char path[] = "docs/c/strings/lesson.txt";
    const char *slash = strrchr(path, '/');

    const char *filename = (slash != NULL) ? slash + 1 : path;
    printf("File name: %s\n", filename);

    return 0;
}

Output

File name: lesson.txt

Search User Input Top ↑

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

int main(void) {
    char text[100];
    char ch;

    printf("Enter a string: ");
    if (fgets(text, sizeof text, stdin) == NULL) {
        return 1;
    }
    text[strcspn(text, "\n")] = '\0';

    printf("Enter a character: ");
    if (scanf(" %c", &ch) != 1) {
        return 1;
    }

    char *pos = strrchr(text, ch);

    if (pos != NULL) {
        printf("Last occurrence at index %td.\n", pos - text);
    } else {
        printf("Character not found.\n");
    }

    return 0;
}

Preserved Example: Keep the Path Through the Last Slash Top ↑

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

int main(void) {
    char path[] = "file/path/filename.txt";
    char *slash = strrchr(path, '/');

    if (slash != NULL) {
        slash[1] = '\\0';
        printf("Directory path: %s\n", path);
    }

    return 0;
}

Preserved Example: Count Occurrences with Repeated strrchr() Searches Top ↑

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

int main(void) {
    char remaining[] = "plus2net is a great site for tutorials";
    const char target = 't';
    int count = 0;
    char *match;

    while ((match = strrchr(remaining, target)) != NULL) {
        count++;
        *match = '\\0';
    }

    printf("Occurrences of '%c': %d\n", target, count);
    return 0;
}

This mirrors the original backward-search technique. It intentionally works on a mutable copy because each found character is replaced by the null terminator before the next strrchr() call.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer