Strrchr() function in C
×


Strrchr() function in C

64

The strrchr() function in C is a useful tool for locating the last occurrence of a character in a string.

 Syntax  of strrchr():

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

This function searches for the last occurrence of character in the string str and returns a pointer to the location where it is found.

If the character is not located, it returns a null pointer, indicating that the character is absent in the string.

Example:

//Program for strrchr()
#include<stdio.h> 
#include<string.j 

int main() {
    char str[] = "hello world";
    char *ptr = strrchr(str, 'l');

    if (ptr != NULL) {
        printf("Last occrance 'l' is at position: 9: %ld\n", ptr - str);
    } else {
        printf("Character 'l' not found\n");
    }

    return 0;
}

Output:

Last occrance 'l' is at position: 9

In this program:

We incorporate the essential header files stdio.h and string.h, then declare a character array str holding the string "hello world".

We call strrchr() with the string str and the character 'l'.

If strrchr() finds the character, it returns a pointer to its location in the string.

We calculate its position by subtracting the base address of str.

If the character is not found, strrchr() returns NULL.

This indicates that the last occurrence of the character 'l' in the string "hello world" is at index 9 (0-based indexing).



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments