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.

Mayur22kar said:   4 years ago
Thanks @Srikanth.

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)

Suraj said:   8 years ago
Nice explanation @Srikanth.

Prateek said:   8 years ago
Thanks @Srikanth.

Mostafa Yasin said:   8 years ago
Thanks @Ashish.

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

Rajes said:   9 years ago
Thanks @Srikanth.

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.

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


Post your comments here:

Your comments will be displayed after verification.