C Programming - Library Functions - Discussion

3. 

Which standard library function will you use to find the last occurance of a character in a string in C?

[A]. strnchar()
[B]. strchar()
[C]. strrchar()
[D]. strrchr()

Answer: Option D

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.


Suren said: (Sep 9, 2010)  
Why we are putting -str there in printf statement? Please help me.

Pruthvi said: (Jul 22, 2011)  
Why -str is used?

Athinivas said: (Jul 24, 2011)  
@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..

Srikanth said: (Jul 29, 2011)  
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.

Ravi said: (Aug 17, 2011)  
Thanks srikanth.

Kiran said: (Sep 3, 2011)  
Excellent srikanth.

Sonu said: (Dec 20, 2011)  
Rightly said srikanth.

Renu Gurpreet said: (Dec 29, 2011)  
Thanks @Srikanth.

Neha said: (May 23, 2012)  
Thanks shrikant it is really very easy when you explained it.

Ashish said: (Jun 16, 2014)  
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.

Rajes said: (Jun 23, 2016)  
Thanks @Srikanth.

Ishwarya said: (Feb 28, 2017)  
Thank you so much @Srikanth.

Mostafa Yasin said: (Mar 13, 2017)  
Thanks @Ashish.

Prateek said: (May 20, 2017)  
Thanks @Srikanth.

Suraj said: (Jul 4, 2017)  
Nice explanation @Srikanth.

Sridhar said: (Mar 6, 2018)  
Why the array range from 50 to 66 @Srikanth.

Suchi said: (Jul 23, 2018)  
I am not getting can anyone explain option D.

Mayur22Kar said: (Jul 23, 2021)  
Thanks @Srikanth.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.