Pages

Friday 4 July 2014

C – strchr() function

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

Example program for strchr() function in C:

    • In this program, strchr( ) function is used to locate first occurrence of the character ‘i’ in the string ”This is a string for testing”. Character ‘i’ is located at position 3 and pointer is returned at first 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 = strchr (string,'i');

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

   return 0;
}

Output:

Character i is found at position 3
First occurrence of character “i” in “This is a string for testing” is “is is a string for testing”
    • If you want to find every occurrence of a character in a given string, you can use below C program.
#include <stdio.h>
#include <string.h>
int main ()
{
  char string[55] ="This is a string for testing";
  char *p;
  int k = 1;
  p = strchr (string,'i');
  while (p!=NULL)
  {
    printf ("Character i found at position %d\n",p-string+1);
    printf ("Occurrence of character \"i\" : %d \n",k);
    printf ("Occurrence of character \"i\" in \"%s\" is \"%s" \
            "\"\n",string, p);
    p=strchr(p+1,'i');
    k++;
  }
  return 0;
}

Output:

Character i is found at position 3
Occurrence of character “i” : 1
Occurrence of character “i” in “This is a string for testing” is “is is a string for testing”
Character i is found at position 6
Occurrence of character “i” : 2
Occurrence of character “i” in “This is a string for testing” is “is a string for testing”
Character i is found at position 14
Occurrence of character “i” : 3
Occurrence of character “i” in “This is a string for testing” is “ing for testing”
Character i is found at position 26
Occurrence of character “i” : 4
Occurrence of character “i” in “This is a string for testing” is “ing”

0 comments:

Post a Comment