C strchr() and strrchr() function

Both the strchr() and strrchr() functions are used to search any character inside a string. They will return the characters after matched character. In case of strchr(), the searching is perform normally but in case of strrchr() the searching occurs in reverse direction. Here, we will learn about strchr() and strrchr() string functions in C.

using strchr() function in C

strchr() function is used to search a character inside a string. It gives another string containing the characters after the matched character of the first string. Syntax of strchr() is given here.

// syntax of strchr() string function

char *strchr(char *String, int ch);

Here we have used char with data type int because strchr() will convert the character to integer for better searching when we use char inside the strchr() function. Now, consider the following example for better understanding.

// strchr() function in C
#include <stdio.h>
#include <string.h>
int main(){
  char myString[50] = "I am learning from competitiveprogrammer.com";

  printf ("%s\n", strchr(myString, 'g'));   // search for char g

  return 0;
}

Output of strchr() function program

C strchr() and strrchr() function, strchr() function in C

using strrchr() function in C

strrchr() string function is also used to search a character inside a string like strchr() function, but it searches the character inside the string in reverse order.  Syntax of strrchr() string function is given bellow.

// syntax of strrchr() string function

char *strrchr(char *mainString, int ch);

Now, lets see an example of C program using strrchr() string function.

// strrchr() function in C
#include <stdio.h>
#include <string.h>
int main(){
  char myString[50] = "Competitiveprogrammer.com is best for learn C";

  printf ("%s", strrchr(myString, '.'));

  return 0;
}

You will see the output like this.

strrchr() function in C