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.

Prototype

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

Parameter

This function has the following parameter.

str
C string.
character
Character to be located.




Return

A pointer to the first occurrence of character in str.

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

Example


#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);
  pch=strchr(str,'s');
  while (pch!=NULL){
    printf ("found at %d\n",pch-str+1);
    pch=strchr(pch+1,'s');
  }
  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.