strchr() Function in C: Finding Characters in Strings

Rumman Ansari   Software Engineer   2024-07-05 04:24:36   7850  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

strchr() function returns pointer to the first occurrence of the character in a given string.

Syntax

char *strchr(const char *str, int ch);

Returns

The strchr( ) function returns a pointer to the first occurrence of the low-order byte of ch in the string pointed to by str. If no match is found, a null pointer is returned.

Program 1

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 
#include 
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" 

Note: If you want to find each occurrence of a character in a given string, you can use below C program.

Program 2

 
#include 
#include 
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 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 found at position 6
Occurrence of character "i" : 2
Occurrence of character "i" in "This is a string for testing" is "is a string fo
r testing"
Character i found at position 14
Occurrence of character "i" : 3
Occurrence of character "i" in "This is a string for testing" is "ing for testin
g"
Character i found at position 26
Occurrence of character "i" : 4
Occurrence of character "i" in "This is a string for testing" is "ing"
Press any key to continue . . .

Program 3

#include 
#include 

int main(void)
{
char *poi;
poi = strchr("this is a test", ' ');
printf(poi);
return 0;
}

Output

 is a test