C++ memchr() Function: Complete Guide

The memchr() function in C++ searches for the first occurrence of a character in a specified number of characters.

C++ memchr() Function

C++ memchr() is a built-in function that is used for string handling. The memchr() function is defined under the string.h header file. The memchr() function finds the first occurrence of a character in the string within a specified number of characters in the string. There are 3 arguments in this function. Terminating null characters is not considered.

Syntax

const void* memchr(const void* tofind_ptr, int ch, size_t count);

Parameters

It takes 3 parameters tofind_ptr, ch, and count. All the parameters are for different purposes. The first parameter tofind_ptr points to the object to be searched.

The second one is the character that we are looking for, and the third parameter count is for the number of characters to be searched.

Return Value

It returns a point that locates the character if the character is found. In all other cases, it returns a null pointer. It first converts ch to unsigned char and locates its first occurrence in the first count characters of the object pointed to by tofind_ptr.

Example programs on strpbrk() function in C++

Example 1: Write a program to show the working of the memchr() function.

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
  char k[] = "I am a Messi fan!";
  char q = 'M';
  int count = 12;
  if (memchr(k, q, count))
  {
    cout << "The character 'M' is present in the first string within " << count << " characters";
  }
  else
  {
    cout << "Sorry character not present!";
  }
}

Output

The character 'M' is present in the first string within 12 characters.

Example 2: Write a program to pass a set of characters not present in another string using the strpbrk() function and show the output.

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
  char k[] = "I am a Messi fan!";
  char q = 'M';
  int count = 3;
  if (memchr(k, q, count))
  {
    cout << "The character 'M' is present in the first string within " << count << " characters";
  }
  else
  {
    cout << "Sorry character not present!";
  }
}

Output

Sorry character not present!

In the second example, space is counted as the 3rd character.

Conclusion

C++ memchr() function looks for the first occurrence of ch within the count characters in the array pointed to by the buffer. The return value points to a location of the first occurrence of ch, or NULL if ch isn’t found.

See also

C++ strcncmp()

C++ strcmp()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.