C programming string.h function - char *strchr(const char *str, int c)

The strchr() function is defined in the string.h header file in C programming.

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 to the first occurrence of the character c in the string, or a null pointer if the character is not found.

Here is the syntax of the strchr() function:

char *strchr(const char *str, int c)
Sour‮gi.www:ec‬iftidea.com
  • str: This is the C string to be searched.
  • c: This is the character to be searched in str.

The strchr() function can be used as follows:

#include <string.h>

int main() {
   char str[] = "Hello, World!";
   char *ptr = strchr(str, 'W');
   
   if (ptr != NULL) {
      printf("Found the character 'W' at position %ld\n", ptr - str);
   }
   else {
      printf("The character 'W' was not found\n");
   }

   return 0;
}

Output:

Found the character 'W' at position 7