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 1 of 2.

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)

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

char str[30] = "12345678910111213";

Base address of str is 0.
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"
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16.

So,
strrchr(str,'2') returns 14. (the address of the last occurrence).

And we know str=0(base address).

(strrchr(str,'2') - str )=(14-0)=14.

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..

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

Neha said:   1 decade ago
Thanks shrikant it is really very easy when you explained it.

Suchi said:   7 years ago
I am not getting can anyone explain option D.
(1)

Sridhar said:   7 years ago
Why the array range from 50 to 66 @Srikanth.
(1)

ISHWARYA said:   8 years ago
Thank you so much @Srikanth.

Suraj said:   8 years ago
Nice explanation @Srikanth.

Sonu said:   1 decade ago
Rightly said srikanth.


Post your comments here:

Your comments will be displayed after verification.