C++ wmemchr()

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

The wmemchr() function is defined in <cwchar> header file.

wmemchr() prototype

const wchar_t* wmemchr( const wchar_t* ptr, wchar_t ch, size_t count );
wchar_t* wmemchr( wchar_t* ptr, wchar_t ch, size_t count );

The wmemchr() function takes three arguments: ptr, ch and count. It locates the first occurrence of ch in the first count wide characters of the object pointed to by ptr.

If the value of count is zero, the function returns a null pointer.

wmemchr() Parameters

  • ptr: Pointer to the wide character array to be searched for.
  • ch: Wide character to search for.
  • count: Number of wide characters to search.

wmemchr() Return value

If the character is found, the wmemchr() function returns a pointer to the location of the wide character, otherwise returns null pointer.

Example: How wmemchr() function works?

#include <cwchar>
#include <clocale>
#include <iostream>
using namespace std;

int main()
	setlocale(LC_ALL, "en_US.utf8");

	wchar_t ptr[] = L"\u0102\u0106\u0126\u01f6\u021c\u0246\u0376\u024a";
	wchar_t ch = L'Ħ';
	int count = 5;
	if (wmemchr(ptr,ch, count))
		wcout << ch << L" is present in first " << count << L" characters of \"" << ptr << "\"";
		wcout << ch << L" is not present in first " << count << L" characters of \"" << ptr << "\"";
	return 0;

When you run the program, the output will be:

Ħ is present in first 5 characters of "ĂĆĦǶȜɆͶɊ"
Did you find this article helpful?