AppDividend
Latest Code Tutorials

C++ memchr() Function Example | std::memchr in C++

0

C++ memchr() is an inbuilt function that is used for string handling. It 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 are not considered.

C++ memchr() Function

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

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 which is to be searched.

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

Return Value

It returns a point which 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 character which is not present in another string using 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 Reply

Your email address will not be published.

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