Open In App

std::memchr in C++

Last Updated : 29 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
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++
// CPP program to illustrate memchr()
#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    // defining string and a character
    char sr[] = "This is a sample";
    char ch = 's';
    int count = 13;

    // using memchr to check for the presence of 's' in sr
    if (memchr(sr, ch, count))
        cout << ch << " is present in first " << count
             << " characters of \"" << sr << "\"";
    else
        cout << ch << " is not present in first " << count
             << " characters of \"" << sr << "\"";

    return 0;
}

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


Next Article
Article Tags :
Practice Tags :

Similar Reads