C string library function strchr()


In this article, you will how to use C string library function strchr() which is used to search strings with example and step by step explanation.

C string library function strchr()

strchr() function is the standard string handling function defined under string-handling library string.h. Therefore, we should include string library header file in the program before using it.

#include<string.h>

Whenever you want to locate the particular character in the string, you can use c library function strchr().

Function prototype of C string library function strchr)

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

where,

             str = string in which you want to search

             ch = character you want to locate

As we have already mentioned, this function locates the first occurrence of character ch in the string str.

This function returns a pointer to the character ch in the string str, if the character is found otherwise, a null pointer is returned.

C string library function strchr() Example

/*Use of C library function strchr( )*/

#include<stdio.h>
#include<string.h>

int main()
{
   const char *str = "trytoprogram.com"; //initialization of char pointer
   char ch; //declare char variable

   printf("String = \"%s\"\n\n", str);

   //taking character input from user
   printf("Enter a character you want to locate: ");
   scanf("%c", &ch);

   //if condition for checking character in the string
   if( strchr( str, ch ) != NULL ) //checking for null pointer
      printf("\n\'%c\' was found in \"%s\".\n", ch, str);

   //if character was not found in the string
   else
     printf("\n\'%c\' was not found in \"%s\".\n", ch, str);

   return 0;
}

Output

#1

c strchr output1

#2

c strchr output2

Explanation

In the above program, we searched for a character in the string "trytoprogram.com".

We asked the user to input a character and searched in the string.

The condition for locating the character is to check for the value of pointer returned by strchr() function.

This is all about C library function strchr(), we hope you have understood the concept and use of the function.