C String Functions - C memchr






Copies a character into memory.

void *memchr(const void *str , int c , size_t n );

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

Returns a pointer pointing to the first matching character, or null if no match was found.

Prototype

const void * memchr ( const void * ptr, int value, size_t num );
      void * memchr (       void * ptr, int value, size_t num ); 

Parameter

This function has the following parameter.

ptr
Pointer to the block of memory where the search is performed.
value
Value to be located.
num
Number of bytes to be analyzed.

size_t is an unsigned integral type.

Return

A pointer to the first occurrence of value in the block of memory pointed by ptr. If the value is not found, the function returns a null pointer.





Example


#include <stdio.h>
#include <string.h>
//  ww w  . j  av a 2s.c o m
int main (){
  char * pch;
  char str[] = "Example string";
  pch = (char*) memchr (str, 'p', strlen(str));
  if (pch!=NULL)
    printf ("'p' found at position %d.\n", pch-str+1);
  else
    printf ("'p' not found.\n");
  return 0;
}        

The code above generates the following result.





Example 2


#include <stdio.h>
#include <string.h>
 /*from   w  w w  .  j a  v  a 2  s. c o  m*/
int main(void){
    char str[] = "ABCDEFG";
    char *ps = memchr(str,'D',strlen(str));
    if (ps != NULL)
       printf ("search character found:  %s\n", ps);
    else
       printf ("search character not found\n");
 
    return 0;
}

The code above generates the following result.