Pages

Friday 4 July 2014

C – strrchr() function

  • strrchr( ) function in C returns pointer to the last occurrence of the character in a given string. Syntax for strrchr( ) function is given below.
char *strrchr(const char *str, int character);

Example program for strrchr() function in C:

  • In this program, strrchr( ) function is used to locate last occurrence of the character ‘i’ in the string ”This is a string for testing”. Last occurrence of character ‘i’ is located at position 26 and pointer is returned at last occurrence of the character ‘i’.
#include <stdio.h>
#include <string.h>
int main ()
{
  char string[55] ="This is a string for testing";
  char *p;
  p = strrchr (string,'i');

  printf ("Character i is found at position %d\n",p-string+1);
  printf ("Last occurrence of character \"i\" in \"%s\" is" \
           " \"%s\"",string, p);

   return 0;
}

Output:

Character i is found at position 26
Last occurrence of character “i” in “This is a string for testing” is “ing”

0 comments:

Post a Comment