C++ offers various standard template libraries to be used. One of them is memchr() function which will search for the first occurrence of a character in a specified number of characters.
Template
const void* memchr( const void* ptr, int ch, std::size_t count ); Parameters : ptr : Pointer to the object to be searched for. ch : Character to search for. count : Number of character to be searched for. Return value: If the character is found, the memchr() function returns a pointer to the location of the character, otherwise returns null pointer.
// CPP program to illustrate memchr() #include <cstring> #include <iostream> using namespace std; int main() { char sr[] = "This is a sample"; char ch = 's'; int count = 13; 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:
// CPP program to illustrate memchr() #include <iostream> #include <cstring> int main() { char arr[] = { 'b', 'a', 'd', 'e', 'f', 'A', 'g' }; char* pc = (char*)std::memchr(arr, 'g', sizeof arr); if (pc != NULL) std::cout << "search character found\n"; else std::cout << "search character not found\n"; } |
Output:
search character found
This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
Recommended Posts:
- Iterate over characters of a string in C++
- Difference between int (*p)[3] and int* p[3]?
- 3-way comparison operator (Space Ship Operator) in C++ 20
- How to generate a vector with random values in C++?
- Difference between std::set vs std::vector in C++ STL
- Vector of Maps in C++ with Examples
- Data Conversion in C++
- Length of smallest meeting that can be attended
- Order of execution in initializer list in C++
- Unusual behaviour with character pointers
- Header Guard in C++
- Can we write a print statement within if parentheses?
- Joining Tables using MultiMaps
- If memory allocation using new is failed in C++ then how it should be handled?
- Draw an ellipse divided by straight line into two colored part in C++ Graphics

