C Programming - Library Functions - Discussion

Discussion Forum : Library Functions - General Questions (Q.No. 3)
3.
Which standard library function will you use to find the last occurance of a character in a string in C?
strnchar()
strchar()
strrchar()
strrchr()
Answer: Option
Explanation:

strrchr() returns a pointer to the last occurrence of character in a string.

Example:


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

int main()
{
    char str[30] = "12345678910111213";
    printf("The last position of '2' is %d.\n",
            strrchr(str, '2') - str);
    return 0;
}

Output: The last position of '2' is 14.

Discussion:
18 comments Page 2 of 2.

RENU GURPREET said:   1 decade ago
Thanks @Srikanth.

Sonu said:   1 decade ago
Rightly said srikanth.

Kiran said:   1 decade ago
Excellent srikanth.

Ravi said:   1 decade ago
Thanks srikanth.

Srikanth said:   1 decade ago
In the example it is given that

char str[30]="12345678910111213";

Lets assume the base address of str is 50.
each char takes one byte.
so the array addresses will be from 50 to 66.i.e

"1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3"
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

so,
strrchr(str,'2') returns 64. (the address of the last occurence)

and we know str=50(base address)

( strrchr(str,'2') - str )=(64-50)=14.
(1)

Athinivas said:   1 decade ago
@Pruthvi strrchr() returns pointer to last(first in terms of position)occurence of char u given....so if we subtract the add of that returning pointer with the actual one...we get position...(Since char occupies a single byte)....Thanq u..

Pruthvi said:   1 decade ago
Why -str is used?

Suren said:   1 decade ago
Why we are putting -str there in printf statement? Please help me.


Post your comments here:

Your comments will be displayed after verification.