The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

strrchr() in C

Purpose of strrchr()

strrchr() is one of the inbuilt string function in c programming which is used to find the last occurrence of a character chr in a string str. Simply strrchr() is opposite to strchr().

How strrchr() Works

The following diagram clearly illustrate the working principle of strrchr() inbuilt string function in C.

strrchr() in c

In the above diagram strrchr() takes two parameters. First parameter is a string whereas as second parameter is a character. If a character chr present in a string, then strrchr() will return a string str starting from the last occurrence of a character in a string. If not it returns null.

Syntax - strrchr()

  • strrchr() accepts two parameters.
  • First parameter is a string whereas as second parameter is a character.
  • To use strrchr() inbuilt string function in C, we need to declare #include<string.h> header file.
Syntax
strrchr(str, chr);

C Program - Using strrchr()

Let us work through strrchr() function, In the following program we will find the last occurrence of a character chr in a string str.

c-strrchr.c
#include <stdio.h>
#include<string.h>
int main()
{
char str[] = "DayDreamer";
char chr = 'D', *chpos;
chpos = strrchr(str, chr);
printf("%s",chpos);
return 0;
}
Dreamer

Note:

The above program prints the output if the character ch is present in the source string otherwise returns null.

C Program - Without strrchr()

c-without-strrchr.c
#include <stdio.h>
#include<string.h>
int main()
{
char str[20] = "DayDreamer";
char chr = 'D', i, j, k;
for(i=0; str[i]!='\0'; i++){
//finding length of a string
}
for(j=i-1; j>=0; j--){
if(str[j]==chr)
{
for(k=j; k<i; k++)
printf("%c",str[k]);
return 0;
}
}
return 0;
}
Dreamer

Note:

The above program looks verbose but yields same the result.

Did You Know?

  • strchr() used to find a last occurrence of a character in a string.
  • strrchr() used to find a first occurrence of a character in a string.

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report