strchr() — Search for character

Standards

Standards / Extensions C or C++ Dependencies

ISO C
XPG4
XPG4.2
C99
Single UNIX Specification, Version 3

both  

Format

C:
#include <string.h>

char *strchr(const char *string, int c);
C++:
#include <string.h>

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

General description

The strchr() built-in function finds the first occurrence of c converted to char, in the string *string. The character c can be the NULL character (\0); the ending NULL character of string is included in the search.

The strchr() function operates on NULL-terminated strings. The string argument to the function must contain a NULL character (\0) marking the end of the string.

Returned value

If successful, strchr() returns a pointer to the first occurrence of c (converted to a character) in string.

If the character is not found, strchr() returns a NULL pointer.

Example

CELEBS35
/* CELEBS35                                      

   This example finds the first occurrence of the character p in                
   "computer program".                                                          
                                                                                
 */                                                                             
#include <stdio.h>                                                              
#include <string.h>                                                             
                                                                                
#define SIZE 40                                                                 
                                                                                
int main(void)                                                                  
{                                                                               
  char buffer1[SIZE] = "computer program";                                      
  char * ptr;                                                                   
  int    ch = 'p';                                                              
                                                                                
  ptr = strchr( buffer1, ch );                                                  
  printf( "The first occurrence of %c in '%s' is '%s'\n",                       
            ch, buffer1, ptr );                                                 
                                                                                
}                                                                               
Output
The first occurrence of p in 'computer program' is 'puter program'