strrchr() in C - Source Code Example

In this source code example, we will see how to use the strrchr() function in C programming with an example.

strrchr() Function Overview

The strrchr() function finds the last occurrence of a character in a string. It is in the <string.h> header. When it finds the character, it returns a pointer to the last occurrence. If it doesn't find it, it returns NULL

Key Points: 

- It's in the <string.h> header. 

- It looks for the last occurrence of a character in a string. 

- It gives back a pointer to the character. If not found, it returns NULL.

Source Code Example

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

int main() {
    char str[] = "Hello, World!";
    char ch = 'o';

    char *last_occurrence = strrchr(str, ch);
    if (last_occurrence) {
        printf("Last 'o' is at position: %ld\n", last_occurrence - str);
    } else {
        printf("Didn't find the character.\n");
    }

    return 0;
}

Output

Last 'o' is at position: 8

Explanation

1. We have a string str and a character ch.

2. We use strrchr() to look for the last 'o' in str.

3. If we find it, we show where it is using pointers.

4. If we don't find it, we say so.


Comments