Open In App

std::memchr in C++

Last Updated : 29 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

C++ offers various standard template library functions to be used. One of them is memchr() function which is used to search for the first occurrence of a character in a specified number of characters.

memchr() is defined inside <cstring> header file.

Syntax of memchr()

const void* memchr( const void* ptr, int ch, std::size_t count );

Parameters

  • ptr: Pointer to the object where the search will be performed.
  • ch: Character to search for.
  • count: Number of characters to be searched for.

Return Value

  • If the character is found, the memchr() function returns a pointer to the location of the character otherwise,
  • If the character is not found, it returns the NULL Pointer.

Examples of memchr()

Example 1

The following C++ program illustrates the use of memchr() function to search for a character in a string.

C++





Output

s is present in first 13 characters of "This is a sample"

Example 2

The following C++ program illustrates the use of memchr() function to search for a character in an array of characters.

C++




// CPP program to illustrate memchr()
#include <cstring>
#include <iostream>
using namespace std;
 
int main()
{
    char arr[] = { 'b', 'a', 'd', 'e', 'f', 'A', 'g' };
 
    // checking the presence of 'g'
    char* pc = (char*)memchr(arr, 'g', sizeof arr);
    if (pc != NULL)
        cout << "search character found\n";
    else
        cout << "search character not found\n";
}


Output

search character found

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads