The strchr Function & strrchr function






Syntax:

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

The strchr() function searches for the first occurrence of the character c(an unsigned char)in the string pointed to by the argument str. The function returns a pointer pointing to the first matching character,or null if no match was found.

    #include<stdio.h>

   #include<string.h>

   int main()

    {

     char str[50] = "programming In c";

     char  *pos;

     pos= strchr (str,  'n');

     if(pos)

       printf("\n  n is found in str at position %d", pos);

    else

        printf("\n n is not present in the string");

        }


Output

n is found in str at position 9


The strrchr function

syntax: 

    char  *strrchr(const char  *str, int c);

The strrchr() function searches for the first occurrence of the character c (an unsigned char) beginning at the rear end and working towards the front in the string pointed to by the argument str, i.e the function searches for the last occurrence of the character c and returns a pointer pointing to the last matching character, or null if match was found.

#incliude<stdio.h>

#include<conio.h>

int main()

{

 char str[50] = "programming In c";

char *pos;

pos = strrchr(str, 'n');

if(pos)

    printf("\n the last position of n is : %d", pos-str);

else

   printf("\n  n is not present in the string");

}


Output

  The last position of n is: 13

Comments