C String Functions - C strchr

Searches for a character in a string.

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

Searches for the first occurrence of the character c (an unsigned char) in the string str.

The terminating null character is considered to be part of the string.

Returns a pointer pointing to the first matching character, or null if no match was found. Locate first occurrence of character in string.


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


This function has the following parameter.

C string.
Character to be located.


A pointer to the first occurrence of character in str.

If the character is not found, the function returns a null pointer.


#include <stdio.h>
#include <string.h>
//from www .j ava 2 s. c  om
int main (){
  char str[] = "This is a sample string";
  char * pch;
  printf ("Looking for the 's' character in \"%s\"...\n",str);
  while (pch!=NULL){
    printf ("found at %d\n",pch-str+1);
  return 0;


The code above generates the following result.

Example 2

#include <stdio.h>
#include <string.h>
 /*from  ww w .  j ava 2 s .c o  m*/
int main(void){
  const char *str = "this is a test Test";
  char target = 'T';
  const char *result = str;
  while((result = strchr(result, target)) != NULL) {
    printf("Found '%c' starting at '%s'\n", target, result);
    ++result; // Increment result, otherwise we'll find target at the same location

The code above generates the following result.