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.
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++
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char arr[] = { 'b', 'a', 'd', 'e', 'f', 'A', '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
Last Updated :
29 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...